最新消息:

python中IP地址转换

Python admin 1024浏览 0评论

python中字符串IP地址与数字IP地址的转换:

1、字符串IP地址转换成数字IP地址

# ip ==> 数字
>>> ip2num = lambda x:sum([256**j*int(i) for j,i in enumerate(x.split('.')[::-1])])
>>> ip2num('192.168.0.1')
3232235521

2、数字IP地址转换成字符串IP地址

# 数字 ==> ip # 数字范围[0, 255^4]
>>> num2ip = lambda x: '.'.join([str(x/(256**i)%256) for i in range(3,-1,-1)])
>>> num2ip(3232235521)
'192.168.0.1'

 

ps:python中enumerate函数用于遍历序列中的元素及下标

>>> for i,j in enumerate(('a','b','c')):
 print i,j

 
0 a
1 b
2 c
>>> for i,j in enumerate([1,2,3]):
 print i,j

 
0 1
1 2
2 3
>>> for i,j in enumerate({'a':1,'b':2}):
 print i,j

 
0 a
1 b

>>> for i,j in enumerate('abc'):
 print i,j

 
0 a
1 b
2 c

转载请注明:jinglingshu的博客 » python中IP地址转换


Warning: Use of undefined constant PRC - assumed 'PRC' (this will throw an Error in a future version of PHP) in /usr/share/nginx/html/wp-content/themes/d8/comments.php on line 17
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址