【问题标题】:Convert a bytearray in hex to an IP address python将十六进制的字节数组转换为IP地址python
【发布时间】:2018-03-02 17:56:47
【问题描述】:

我有一个这种格式的IP地址

b'\xd4\xfbuW'

我知道这是一个实际的 IP 地址,但我不知道如何将其打印为普通(如 192.168.1.1)地址,并将其作为字符串存储在我的内存中。如何解码这个十六进制字节数组?

【问题讨论】:

    标签: python ip hex byte


    【解决方案1】:

    您可以使用socket模块函数,例如:

    import socket
    
    ip_string = '192.168.1.1'
    print(socket.inet_aton(ip_string))
    print(socket.inet_ntoa(socket.inet_aton(ip_string)))
    print(socket.inet_pton(socket.AF_INET, '192.168.1.1'))
    print(socket.inet_ntop(
        socket.AF_INET, socket.inet_pton(socket.AF_INET, '192.168.1.1')))
    
    packed_ip = b'\xd4\xfbuW'
    print(socket.inet_ntoa(b'\xd4\xfbuW'))
    

    输出

    b'\xc0\xa8\x01\x01'
    192.168.1.1
    b'\xc0\xa8\x01\x01'
    192.168.1.1
    212.251.117.87
    

    如您所见,192.168.1.1 对应于\xC0\xA8\x01\x01b'\xd4\xfbuW' 对应于212.251.117.87

    【讨论】:

      【解决方案2】:

      你不需要套接字模块。

      如果你有 Python 3.6 或更高版本,你可以使用:

      print('.'.join(f'{c}' for c in b'\xd4\xfbuW'))
      

      否则

      print('.'.join(str(c) for c in b'\xd4\xfbuW'))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        • 2020-06-14
        • 2016-07-05
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多