fixed shebangs in non executable .py files
[nepi.git] / src / nepi / util / ipaddr2.py
1 # -*- coding: utf-8 -*-
2
3 import struct
4 import random
5 import socket
6 import array
7
8 def ipv4_dot2mask(mask):
9     mask = mask.split('.',4) # a.b.c.d -> [a,b,c,d]
10     mask = map(int,mask) # to ints
11     
12     n = 0
13     while mask and mask[0] == 0xff:
14         n += 8
15         del mask[0]
16     
17     if mask:
18         mask = mask[0]
19         while mask:
20             n += 1
21             mask = (mask << 1) & 0xff
22     
23     return n
24
25 def ipv4_mask2dot(mask):
26     mask = ((1L << mask)-1) << (32 - mask)
27     mask = struct.pack(">I",mask)
28     mask = '.'.join(map(str,map(ord,mask)))
29     return mask
30
31 def ipdist(a,b):
32     a = struct.unpack('!L',socket.inet_aton(a))[0]
33     b = struct.unpack('!L',socket.inet_aton(b))[0]
34     d = 32
35     while d and (b&0x80000000)==(a&0x80000000):
36         a <<= 1
37         b <<= 1
38         d -= 1
39     return d
40
41 def ipdistn(a,b):
42     d = 32
43     while d and (b&0x80000000)==(a&0x80000000):
44         a <<= 1
45         b <<= 1
46         d -= 1
47     return d
48
49 def inet_cksum(packet):
50     words = array.array('H')
51     words.fromstring(packet[:len(packet)&~0x1])
52     htons = socket.htons
53     cksum = 0
54     for word in words:
55         cksum += htons(word)
56     if len(packet)&0x1:
57         cksum += ord(packet[-1])
58     cksum &= 0xffffffff
59     cksum = (cksum >> 16) + (cksum & 0xffff)
60     cksum += (cksum >> 16)
61     return ~cksum
62
63 def iphdr(src, dst, datalen, ttl, proto, tos=0, nocksum=False, ipid=0):
64     cksum = 0
65     src = socket.inet_aton(src)
66     dst = socket.inet_aton(dst)
67     hdr = struct.pack('!BBHHHBBH4s4s', 
68         0x45, tos, datalen + 5*4, ipid, 0, 
69         ttl, proto, cksum & 0xffff, src, dst)
70     if not nocksum:
71         cksum = inet_cksum(hdr)
72         hdr = struct.pack('!BBHHHBBH4s4s', 
73             0x45, tos, datalen + 5*4, ipid, 0, 
74             ttl, proto, cksum & 0xffff, src, dst)
75     return hdr
76
77 def igmp(type, mxrt, grp, nocksum=False):
78     cksum = 0
79     grp = socket.inet_aton(grp)
80     ighdr = struct.pack('!BBH4s', type, mxrt, cksum & 0xffff, grp)
81     if not nocksum:
82         cksum = inet_cksum(ighdr)
83         ighdr = struct.pack('!BBH4s', type, mxrt, cksum & 0xffff, grp)
84     return ighdr
85
86 def ipigmp(src, dst, ttl, type, mxrt, grp, noipcksum=False, noigmpcksum=False):
87     igmpp = igmp(type, mxrt, grp, nocksum=noigmpcksum)
88     iph = iphdr(src, dst, len(igmpp), ttl, 2, tos=0xc0, nocksum=noipcksum)
89     return iph+igmpp
90
91