python整数与IP地址转换 [转]

我们有时会将一个整数与IP地址进行互换,用python代码实现很简单
将一个整数如2000000,变为一个IP地址的方式
>>> import socket
>>> import struct
>>> int_ip = 123456789
>>> ip = socket.inet_ntoa(struct.pack('I',socket.htonl(int_ip)))      #int to ip address
'7.91.205.21'
>>> socket.ntohl(struct.unpack("I",socket.inet_aton(str(ip)))[0])     #ip address to int
123456789L

其实这是进制数的转换,我们可以自己写代码
# 整数to IP地址格式
>>> def ch1(num):
             s = []
             for i in range(4):
                  s.append(str(num %256))
                  num /= 256
        return '.'.join(s[::-1])
>>> ch1(123456789)
'7.91.205.21'

用lambda的方式,整数toIP 地址 一行代码搞定
>>> ch2 = lambda x: '.'.join([str(x/(256**i)%256) for i in range(3,-1,-1)])
>>> ch2(123456789)
'7.91.205.21'

用lambda的方式,IP地址转换到整数
>>> ch3 = lambda x:sum([256**j*int(i) for j,i in enumerate(x.split('.')[::-1])])
>>> ch3('7.91.205.21')
123456789

posted on 2012-10-17 00:28  Vovolie  阅读(44619)  评论(1编辑  收藏  举报

导航