77家的会客2010

Python实现IP地址与数值之间互转
Weather:短袖终于可以穿了

   自己写方法:

 def ip2num(ip):
i = 0
result = 0
for num in ip.split("."):
result += int(num)<<((3-i)*8)
i+=1
return result 

def num2ip(num):
li = []
num1 = num>>24
li.append(str(num1))
num2 = ((num>>16)-(num1<<8))
li.append(str(num2))
num3 = ((num>>8)-(num1<<16)-(num2<<8))
li.append(str(num3))
num4 = (num-(num1<<24)-(num2<<16)-(num3<<8))
li.append(str(num4))
return ".".join(li)

其实PY已经有相应的模块了

>>> import socket
>>> import struct
>>> socket.ntohl(struct.unpack('i',socket.inet_aton('192.168.101.2'))[0])
3232261378L
>>> socket.inet_ntoa(struct.pack('i',socket.htonl(3232261378L)))
'192.168.101.2'

(04/18) Today
历史上的今天: [2005/04/28]COLDFUSION保护方法(zt)

[Python实现IP地址与数值之间互转]的回复

Post a Comment~