【问题标题】:Converting negative number to IP address python将负数转换为IP地址python
【发布时间】:2015-06-26 03:04:34
【问题描述】:

我正在尝试将长数字转换为 IP 地址,但 python 不允许我将 -ve 值转换为长数字。以下是我的功能,有人可以帮忙吗?

将ip地址从字符串转换为整数

def get_ip_address_int(ip_address):
    return struct.unpack("!L", socket.inet_aton(ip_address))[0]

# Convert ip adress from integer to string
def get_ip_address_str(ip_address):
    return socket.inet_ntoa(struct.pack('!L',ip_address))

ip_address = -1277278613

非常感谢。

【问题讨论】:

  • 如果你尝试socket.inet_ntoa(struct.pack('!L',(ip_address+2**32)%2**32)会发生什么?
  • 确定:您是否收到 "struct.error: argument out of range"

标签: python-3.x ip ip-address


【解决方案1】:

L 表示 无符号 长。 -1277278613 已签名。假设输入必须是 32 位(ipv4),那么-1277278613 可能会根据字节顺序对应不同的位模式:

>>> socket.inet_ntoa(struct.pack('<i', -1277278613))
'107.70.222.179'
>>> socket.inet_ntoa(struct.pack('>i', -1277278613))
'179.222.70.107'

如果符号没有被保留,那么你也不应该假设网络字节顺序(大端)。

如果您认为输入使用本机字节顺序;你可以使用=(标准尺寸):

>>> socket.inet_ntoa(struct.pack('=i', -1277278613))
'107.70.222.179'

【讨论】:

    猜你喜欢
    • 2011-02-25
    • 1970-01-01
    • 2014-11-07
    • 2020-10-22
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 2017-07-01
    • 2016-01-19
    相关资源
    最近更新 更多