Python 将 IP 字符串打包成字节

Python pack IP string to bytes

我想实现自己的 struct.pack 特定函数,将 IP 字符串(即“192.168.0.1”)打包为 32 位打包值,而不使用内置的 socket.inet_aton在方法中。

我到目前为止:

ip = "192.168.0.1"
hex_list = map(hex, map(int, ip.split('.')))
# hex list now is : ['0xc0', '0xa8', '0x0', '0x01']

我的问题是: 我如何从 ['0xc0', '0xa8', '0x0', '0x01']'\xc0\xa8\x00\x01',(这就是我从 socket.inet_aton(ip) 得到的?

(还有 - 那个字符串中间怎么可能有一个NUL (\x00)?我想我对\x格式)

备选方案:

可以使用ipaddress and to_bytes (python 3.2)吗?

>>> import ipaddress
>>> address = ipaddress.IPv4Address('192.168.0.1')
>>> address_as_int = int(address)
>>> address_as_int.to_bytes(4, byteorder='big')
b'\xc0\xa8\x00\x01'

请注意,您实际上可能只需要整数。

显然可以更短,但想清楚地显示所有步骤:)

您可以使用字符串推导来格式化:

ip = "192.168.0.1"
hex_list = map(int, ip.split('.'))
hex_string = ''.join(['\x%02x' % x for x in hex_list])

或作为一个班轮:

hex_string = ''.join(['\x%02x' % int(x) for x in ip.split('.')])

松散地基于@Stephen 的回答,但是returns 一个带有实际字节的字符串而不是一个带有斜线的字符串:

def pack_ip(ip):
    num_list = map(int, ip.split('.'))
    return bytearray(num_list)

src_ip = pack_ip('127.0.0.255')
print(repr(src_ip))

适用于 Python 2 和 3。Returns 一个 b'' 而不是字符串,匹配 Python3 的最佳实践。