Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 575
Ofer Arial Avatar asked Aug 22 '26 10:08

Ofer Arial


2 Answers

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('.')])
like image 193
Stephen Rauch Avatar answered Aug 25 '26 00:08

Stephen Rauch


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 :)

like image 44
Reut Sharabani Avatar answered Aug 24 '26 23:08

Reut Sharabani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!