1 | #!/usr/local/bin/python |
---|
2 | |
---|
3 | class ip_addr: |
---|
4 | def __init__(self, x): |
---|
5 | if isinstance(x, ip_addr): |
---|
6 | self.ival = x.ival |
---|
7 | elif isinstance(x, int): |
---|
8 | self.ival = x |
---|
9 | elif isinstance(x, long): |
---|
10 | self.ival = (int(x & 0xffffffff)) |
---|
11 | elif isinstance(x, str): |
---|
12 | self.ival = 0 |
---|
13 | sh = 24 |
---|
14 | bytes = x.split(".", 4) |
---|
15 | for b in bytes: |
---|
16 | self.ival |= (int(b) << sh) |
---|
17 | sh -= 8 |
---|
18 | else: |
---|
19 | self.ival = 0 |
---|
20 | |
---|
21 | def __str__(self): |
---|
22 | return "%d.%d.%d.%d" % ((self.ival & 0xff000000) >> 24, |
---|
23 | (self.ival & 0x00ff0000) >> 16, |
---|
24 | (self.ival & 0x0000ff00) >> 8, |
---|
25 | self.ival & 0x000000ff) |
---|
26 | |
---|
27 | def __add__(self, i): |
---|
28 | if isinstance(i, int): return ip_addr(self.ival + i) |
---|
29 | elif isinstance(i, ip_addr): return ip_addr(self.ival + i.ival) |
---|
30 | else: raise ValueError("IP addrs must operate on IP addrs or ints") |
---|
31 | |
---|
32 | def __sub__(self, i): |
---|
33 | if isinstance(i, int): return ip_addr(self.ival - i) |
---|
34 | elif isinstance(i, ip_addr): return ip_addr(self.ival - i.ival) |
---|
35 | else: raise ValueError("IP addrs must operate on IP addrs or ints") |
---|
36 | |
---|
37 | def __and__(self, i): |
---|
38 | if isinstance(i, int): return ip_addr(self.ival & i) |
---|
39 | elif isinstance(i, ip_addr): return ip_addr(self.ival & i.ival) |
---|
40 | else: raise ValueError("IP addrs must operate on IP addrs or ints") |
---|
41 | |
---|
42 | def __or__(self, i): |
---|
43 | if isinstance(i, int): return ip_addr(self.ival | i) |
---|
44 | elif isinstance(i, ip_addr): return ip_addr(self.ival | i.ival) |
---|
45 | else: raise ValueError("IP addrs must operate on IP addrs or ints") |
---|
46 | |
---|
47 | def __xor__(self, i): |
---|
48 | if isinstance(i, int): return ip_addr(self.ival ^ i) |
---|
49 | elif isinstance(i, ip_addr): return ip_addr(self.ival ^ i.ival) |
---|
50 | else: raise ValueError("IP addrs must operate on IP addrs or ints") |
---|
51 | |
---|
52 | def __radd__(self, i): |
---|
53 | return self.__add__(i) |
---|
54 | |
---|
55 | def __rsub__(self, i): |
---|
56 | return self.__sub__(i) |
---|
57 | |
---|
58 | def __rand__(self, i): |
---|
59 | return self.__and__(i) |
---|
60 | |
---|
61 | def __ror__(self, i): |
---|
62 | return self.__or__(i) |
---|
63 | |
---|
64 | def __rxor__(self, i): |
---|
65 | return self.__xor__(i) |
---|
66 | |
---|
67 | def __int__(self): |
---|
68 | return self.ival |
---|
69 | |
---|
70 | def __oct__(self): |
---|
71 | return oct(self.ival) |
---|
72 | |
---|
73 | def __hex__(self): |
---|
74 | return hex(self.ival) |
---|