pythonsocketsip-addressendianness

Convert "little endian" hex string to IP address in Python


What's the best way to turn a string in this form into an IP address: "0200A8C0". The "octets" present in the string are in reverse order, i.e. the given example string should generate 192.168.0.2.


Solution

  • Network address manipulation is provided by the socket module.

    socket.inet_ntoa(packed_ip)

    Convert a 32-bit packed IPv4 address (a string four characters in length) to its standard dotted-quad string representation (for example, ‘123.45.67.89’). This is useful when conversing with a program that uses the standard C library and needs objects of type struct in_addr, which is the C type for the 32-bit packed binary data this function takes as an argument.

    You can translate your hex string to packed ip using struct.pack() and the little endian, unsigned long format.

    s = "0200A8C0"
    
    import socket
    import struct
    addr_long = int(s, 16)
    print(hex(addr_long))  # '0x200a8c0'
    print(struct.pack("<L", addr_long))  # '\xc0\xa8\x00\x02'
    print(socket.inet_ntoa(struct.pack("<L", addr_long)))  # '192.168.0.2'