1
2
3
4
5
6
7
8
9
10
11
12
13
14 __doc__="""Util
15
16 Utility functions for the Confmon Product
17
18 $Id: IpUtil.py,v 1.4 2002/12/18 18:50:47 edahl Exp $"""
19
20 __version__ = "$Revision: 1.4 $"[11:-2]
21
22 import types
23 import re
24 import string
25
26 from Products.ZenUtils.Exceptions import ZentinelException
27
29
30
31 isip = re.compile("^\d+\.\d+\.\d+\.\d+$").search
32 """return match if this is an ip."""
33
34
36 """check that an ip is valid"""
37 if ip == '': return 1
38 try:
39 octs = ip.split('.')
40 except:
41 raise IpAddressError, '%s is not a dot delimited address' % ip
42 retval = 1
43
44 if len(octs) != 4:
45 retval = 0
46 else:
47 for o in octs:
48 try:
49 if not (0 <= int(o) <= 255):
50 retval = 0
51 except:
52 retval = 0
53 if not retval:
54 raise IpAddressError, "%s is an invalid address" % ip
55 return retval
56
57
59 """convert a string ip to number"""
60 checkip(ip)
61 octs = ip.split('.')
62 octs.reverse()
63 i = 0L
64 for j in range(len(octs)):
65 i += (256l ** j) * int(octs[j])
66 return i
67
68 _masks = (
69 0x000000ffL,
70 0x0000ff00L,
71 0x00ff0000L,
72 0xff000000L,
73 )
74
75
77 """get just the ip from an ip mask pair like 1.1.1.1/24"""
78 return ipmask.split("/")[0]
79
80
82 """convert a number ip to a string"""
83 o = []
84 for i in range(len(_masks)):
85 t = ip & _masks[i]
86 o.append(str(t >> (i*8)))
87 o.reverse()
88 return '.'.join(o)
89
90
92 """convert hex number (0xff000000 of netbits to numeric netmask (8)"""
93 return maskToBits(hexToMask(hex))
94
95
97 '''converts a netmask represented in hex to octets represented in
98 decimal. e.g. "0xffffff00" -> "255.255.255.0"'''
99
100 if hex.find('x') < 0:
101 return "255.255.255.255"
102
103 hex = list(hex.lower().split('x')[1])
104 octets = []
105 while len(hex) > 0:
106 snippit = list(hex.pop() + hex.pop())
107 snippit.reverse()
108 decimal = int(string.join(snippit, ''), 16)
109 octets.append(str(decimal))
110
111 octets.reverse()
112 return string.join(octets, '.')
113
114
116 """convert string rep of netmask to number of bits"""
117 if type(netmask) == types.StringType and netmask.find('.') > -1:
118 test = 0xffffffffL
119 if netmask[0]=='0': return 0
120 masknumb = numbip(netmask)
121 for i in range(32):
122 if test == masknumb: return 32-i
123 test = test - 2 ** i
124 return None
125 else:
126 return int(netmask)
127
128
130 """convert integer number of netbits to string netmask"""
131 masknumb = 0L
132 netbits=int(netbits)
133 for i in range(32-netbits, 32):
134 masknumb += 2L ** i
135 return masknumb
136
137
140
141
143 """get network address of ip as string netmask is in form 255.255.255.0"""
144 checkip(ip)
145 ip = numbip(ip)
146 if 0 < int(netmask) <= 32:
147 netmask = bitsToMaskNumb(netmask)
148 else:
149 checkip(netmask)
150 netmask = numbip(netmask)
151 return ip & netmask
152
153
155 """return network number as string"""
156 return strip(getnet(ip, netmask))
157