Python:将数据包对象/ inet对象转换为32位整数

问题描述:

我有IPv4地址并希望将其转换为32位整数。 我能够使用socket.inet_ntop将IPv4地址转换为字符串,然后将该字符串转换为32位整数
但有没有直接的方法?Python:将数据包对象/ inet对象转换为32位整数

其基本形式为的IPv4地址是网络字节顺序中的32位整数。 我假设你有它作为一个字节序列(因为这是你通常会交给inet_ntop)。

你需要将它转换成一个python整数是struct模块及其unpack方法以及“!I”格式规范(表示网络字节顺序,无符号32位整数)。看到这个代码:

from socket import inet_ntop, inet_pton, AF_INET 
from struct import unpack 

ip = inet_pton(AF_INET, "192.168.1.42") 
ip_as_integer = unpack("!I", ip)[0] 
print("As string[{}] => As bytes[{}] => As integer[{}]".format(
     inet_ntop(AF_INET, ip), ip, ip_as_integer)) 

你当然也可以重建整数按字节:

ip_as_integer = (ip[0] << 24) | (ip[1] << 16) | (ip[2] << 8) | ip[3]