网上找了些python做IP地址转换的方法,python2.5可以正常使用,
蛋python2.6以上经常会报错OverflowError: can't convert negative number to unsigned long
仔细看了下,应该是因为socket.htonl做了限制,不再支持负数转换了
所以转换时需要先把负数转换成long,再做地址转换
def str2int(str):
uint = socket.ntohl(struct.unpack("I",socket.inet_aton(str))[0])
# 先得到负数,再转换一下
return struct.unpack("i", struct.pack('I', uint))[0]
def num2str(ip):
if ip < 0:
ip = struct.unpack("I", struct.pack('i', ip))[0]
return socket.inet_ntoa(struct.pack('I',socket.htonl(ip)))