long integer python_python中实现IP的str与long integer型互换的二个方法

python中实现IP的str与long integer型互换的二个方法,有需要的朋友可以参考下。

方法一:

网上说得比较多的一种方法 代码如下:

def ip2int (addr):

return struct.unpack('I',struct.pack('i',(socket.ntohl(struct.unpack('i', socket.inet_aton(addr))[0]))))[0]

def int2ip (addr):

return socket.inet_ntoa(struct.pack('i',socket.htonl(addr)))

ip = "192.168.1.213"

intip = 3232235823

print "%s to int is %d" % (ip, ip2int(ip))

print "%d to str is %s" % (intip, int2ip(intip))

方法二: 代码如下:

def dottedQuadToNum(ip):

"convert decimal dotted quad string to long integer"

hexn = ''.join(["%02X" % long(i) for i in ip.split('.')])

return long(hexn, 16)

def numToDottedQuad(n):

"convert long int to dotted quad string"

d = 256 * 256 * 256

q = []

while d > 0:

m,n = divmod(n,d)

q.append(str(m))

d = d/256

return '.'.join(q)

print dottedQuadToNum("192.168.1.47")

print numToDottedQuad(3232235823)

说明:

1)、方法一在windows下运行正常,在ubuntu中测试出错:struct.error: long too large to convert to int。

2)、方法二在windows、ubuntu均测试通过。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值