2 Various utility functions used in the nattraverso package.
4 @author: Raphael Slinckx
5 @copyright: Copyright 2005
7 @contact: U{raphael@slinckx.net<mailto:raphael@slinckx.net>}
12 def is_rfc1918_ip(ip):
14 Checks if the given ip address is a rfc1918 one.
16 @param ip: The ip address to test
17 @type ip: a string "x.x.x.x"
18 @return: True if it's a LAN address, False otherwise
20 if isinstance(ip, basestring):
21 ip = _ip_to_number(ip)
23 for net, mask in _nets:
31 Checks if the given ip address is bogus, i.e. 0.0.0.0 or 127.0.0.1.
33 @param ip: The ip address to test
34 @type ip: a string "x.x.x.x"
35 @return: True if it's bogus, False otherwise
37 return ip.startswith('0.') or ip.startswith('127.')
39 def _ip_to_number(ipstr):
41 Translate a string ip address to a packed number.
43 @param ipstr: the ip address to transform
44 @type ipstr: a string "x.x.x.x"
45 @return: an int32 number representing the ip address
47 net = [ int(digit) for digit in ipstr.split('.') ] + [ 0, 0, 0 ]
49 return ((((((0L+net[0])<<8) + net[1])<<8) + net[2])<<8) +net[3]
51 # List of rfc1918 net/mask
52 _rfc1918_networks = [('127', 8), ('192.168', 16), ('10', 8), ('172.16', 12)]
53 # Machine readable form of the above
54 _nets = [(_ip_to_number(net), (2L**32 -1)^(2L**(32-mask)-1))
55 for net, mask in _rfc1918_networks]