将 IP 地址转换为 python 中的字节

Converting IP address into bytes in python

假设我在 python

中有一个 IP 地址
addr = '164.107.113.18'

如何将 IP 地址转换为 4 个字节?

使用socket.inet_aton:

>>> import socket
>>> socket.inet_aton('164.107.113.18')
'\xa4kq\x12'
>>> socket.inet_aton('127.0.0.1')
'\x7f\x00\x00\x01'

这个 returns 一个字节串(或 Python 3.x 上的 bytes 对象),您可以从中获取字节。或者,您可以使用 struct 获取每个字节的整数值:

>>> import socket
>>> import struct
>>> struct.unpack('BBBB', socket.inet_aton('164.107.113.18'))
(164, 107, 113, 18)

使用 ,但这是另一种方法:

ip = '192.168.1.1'
ip_as_bytes = bytes(map(int, ip.split('.')))

编辑:糟糕,这只是 Python 3.X。对于 Python 2.X

ip = '192.168.1.1'
ip_as_bytes = ''.join(map(chr,map(int,ip.split('.'))))

您最好还是使用 ,但是,考虑到它的效率:

>>> timeit.timeit("socket.inet_aton('164.107.113.18')",setup='import socket')
0.22455310821533203
>>> timeit.timeit("''.join(map(chr,map(int,'164.107.113.18'.split('.'))))")
3.8679449558258057