Search code examples
pythonip-addresspackunpackinet-aton

Python pack IP string to bytes


I want to kind of implement my own struct.pack specific function to pack an IP string (i.e. "192.168.0.1") to a 32-bit packed value, without using the socket.inet_aton built in method.

I got so far:

ip = "192.168.0.1"
hex_list = map(hex, map(int, ip.split('.')))
# hex list now is : ['0xc0', '0xa8', '0x0', '0x01']

My question is: How do I get from that ['0xc0', '0xa8', '0x0', '0x01'] to '\xc0\xa8\x00\x01', (this is what I'm getting from socket.inet_aton(ip)?

(And also - How is it possible that there is a NUL (\x00) in the middle of that string? I think I lack some understanding of the \x format)


Solution

  • You can use string comprehension to format as you like:

    ip = "192.168.0.1"
    hex_list = map(int, ip.split('.'))
    hex_string = ''.join(['\\x%02x' % x for x in hex_list])
    

    or as a one liner:

    hex_string = ''.join(['\\x%02x' % int(x) for x in ip.split('.')])