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)
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('.')])
An alternative:
Can you use ipaddress and to_bytes (python 3.2)?
>>> import ipaddress
>>> address = ipaddress.IPv4Address('192.168.0.1')
>>> address_as_int = int(address)
>>> address_as_int.to_bytes(4, byteorder='big')
b'\xc0\xa8\x00\x01'
Note that you may actually only need the integer.
Can be shorter obviously, but wanted to show all steps clearly :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With