Add timestamp offset for block header
[p2pool.git] / nattraverso / utils.py
1 """
2 Various utility functions used in the nattraverso package.
3
4 @author: Raphael Slinckx
5 @copyright: Copyright 2005
6 @license: LGPL
7 @contact: U{raphael@slinckx.net<mailto:raphael@slinckx.net>}
8 @version: 0.1.0
9 """
10 __revision__ = "$id"
11
12 def is_rfc1918_ip(ip):
13     """
14     Checks if the given ip address is a rfc1918 one.
15     
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
19     """
20     if isinstance(ip, basestring):
21         ip = _ip_to_number(ip)
22     
23     for net, mask in _nets:
24         if ip&mask == net:
25             return True
26     
27     return False
28
29 def is_bogus_ip(ip):
30     """
31     Checks if the given ip address is bogus, i.e. 0.0.0.0 or 127.0.0.1.
32     
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
36     """
37     return ip.startswith('0.') or ip.startswith('127.')
38
39 def _ip_to_number(ipstr):
40     """
41     Translate a string ip address to a packed number.
42     
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
46     """
47     net = [ int(digit) for digit in ipstr.split('.') ] + [ 0, 0, 0 ]
48     net = net[:4]
49     return  ((((((0L+net[0])<<8) + net[1])<<8) + net[2])<<8) +net[3]
50
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]
56