IP address to binary conversion

al.alexiev at gmail.com al.alexiev at gmail.com
Sat May 9 12:23:08 EDT 2020


Hi Alan,

Yes, agreed that any '!I' or '!L' combination will work on different type of platforms in a consistent manner, when applied in both directions.

I was referring to Alex Martelli's output, where the conversion back to IP seems to be reversed, even with '!L', which means that he's already with a little-endian byte order and using 'L' or '<L' for the unpacking...

A more detailed example:
>>> ip = '1.2.168.0'
>>> struct.unpack('L', socket.inet_aton(ip))[0]
11010561
>>> struct.unpack('<L', socket.inet_aton(ip))[0]
11010561
>>> struct.unpack('!L', socket.inet_aton(ip))[0]
16951296
>>>
>>> socket.inet_ntoa(struct.pack('!L',11010561))
'0.168.2.1'
>>> socket.inet_ntoa(struct.pack('<L',11010561)) <-- for that specific case
'1.2.168.0'
>>> socket.inet_ntoa(struct.pack('!L',16951296))
'1.2.168.0'
>>>


Greets,
Alex


More information about the Python-list mailing list