由ip和掩码长度判断网段范围
#!/usr/bin/env: pythonimport reimport structclass CIDRHelper: @staticmethod def start(): print "Hello" def ipFormatChk(self, ip_str): pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b" if re.match(pattern, ip_str): return True else: return False def masklenChk(self, masklen): if masklen > 0 and masklen < 32: return true else: return false def Parse(self, ip, masklen): if False == self.ipFormatChk(ip) : return False ips = ip.split(".") binip = 0 for id in ips: binip = binip << 8 binip += int(id) mask = (1 << 32) - 1 - ((1<<(32-masklen))-1) a,b,c,d = struct.unpack('BBBB', struct.pack('>I',(binip & mask))) print ".".join([str(a),str(b),str(c),str(d)]) a,b,c,d = struct.unpack('BBBB', struct.pack('>I',(binip & mask)+(2<<(32-masklen-1)) - 1)) print ".".join([str(a),str(b),str(c),str(d)])ch = CIDRHelper()ch.Parse("183.60.143.187",28)##python a.py#183.60.143.176#183.60.143.191#
?网上查询:http://jodies.de/ipcalc