Python IP地址转整数和整数转IP地址

参考:http://www.cnblogs.com/vovlie/archive/2012/10/17/2727029.html

IP地址转整数

代码:

[root@ops-ip-statistic]# cat iptonum.py 
#!/usr/bin/env python
import sys
ip=sys.argv[1]
ch3 = lambda x:sum([256**j*int(i) for j,i in enumerate(x.split('.')[::-1])])
num=ch3(ip)
print(num)

实例:

[root@ops-ip-statistic ]# python iptonum.py 114.114.114.114
1920103026

整数转IP地址

代码:

[root@ops-ip-statistic]# cat numtoip.py 
#!/usr/bin/env python
import sys
num=int(sys.argv[1])
ch2 = lambda x: '.'.join([str(x/(256**i)%256) for i in range(3,-1,-1)])
ip=ch2(num)
print(ip)

实例:

[root@ops-ip-statistic]# python numtoip.py 1920103026
114.114.114.114

你可能感兴趣的:(Python)