Ticket #45: spanning tree deployment
[nepi.git] / src / nepi / util / ipaddr2.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 import struct
4
5 def ipv4_dot2mask(mask):
6     mask = mask.split('.',4) # a.b.c.d -> [a,b,c,d]
7     mask = map(int,mask) # to ints
8     
9     n = 0
10     while mask and mask[0] == 0xff:
11         n += 8
12         del mask[0]
13     
14     if mask:
15         mask = mask[0]
16         while mask:
17             n += 1
18             mask = (mask << 1) & 0xff
19     
20     return n
21
22 def ipv4_mask2dot(mask):
23     mask = ((1L << mask)-1) << (32 - mask)
24     mask = struct.pack(">I",mask)
25     mask = '.'.join(map(str,map(ord,mask)))
26     return mask
27
28 def ipdist(a,b):
29     a = struct.unpack('!L',socket.inet_aton(a))[0]
30     b = struct.unpack('!L',socket.inet_aton(b))[0]
31     d = 32
32     while d and (b&0x80000000)==(a&0x80000000):
33         a <<= 1
34         b <<= 1
35         d -= 1
36     return d
37
38 def ipdistn(a,b):
39     d = 32
40     while d and (b&0x80000000)==(a&0x80000000):
41         a <<= 1
42         b <<= 1
43         d -= 1
44     return d
45