将IP字符串转换为数字,反之亦然 [英] Convert an IP string to a number and vice versa
本文介绍了将IP字符串转换为数字,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用python将一个作为 str
的IP地址转换为十进制数,反之亦然?
How would I use python to convert an IP address that comes as a str
to a decimal number and vice versa?
例如,对于IP 186.99.109.000< type'str'>
,我想有一个十进制或二进制形式,易于存储在数据库中,然后检索它。
For example, for the IP 186.99.109.000 <type'str'>
, I would like to have a decimal or binary form that is easy to store in a database, and then retrieve it.
推荐答案
将IP字符串转换为long integer:
converting an IP string to long integer:
import socket, struct
def ip2long(ip):
"""
Convert an IP string to long
"""
packedIP = socket.inet_aton(ip)
return struct.unpack("!L", packedIP)[0]
其他方式:
>>> socket.inet_ntoa(struct.pack('!L', 2130706433))
'127.0.0.1'
这篇关于将IP字符串转换为数字,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文