3

我想实现我自己的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

4

3 回答 3

2

您可以根据需要使用字符串理解来格式化:

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('.')])
于 2017-01-15T17:47:29.093 回答
1

替代:

你可以使用ipaddressand (python 3.2)吗?to_bytes

>>> 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'

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

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

于 2017-01-15T17:37:22.913 回答
1

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

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 中工作。返回一个b''而不是字符串,匹配 Python3 的最佳实践。

于 2019-03-28T23:54:22.780 回答