IP address to binary conversion
Alan Bawden
alan at csail.mit.edu
Sat May 9 01:07:15 EDT 2020
al.alexiev at gmail.com writes:
> Just for the records and to have a fully working bidirectional solution:
>
> >>> ip
> '10.44.32.0'
> >>> struct.unpack('L', socket.inet_aton(ip))[0]
> 2108426
> >>> socket.inet_ntoa(struct.pack('<L', 2108426))
> '10.44.32.0'
> >>>
>
> Good luck ;-)
This will not work as expected on a big-endian machine, because 'L' means
_native_ byte order, but '<L' means little-endian byte order. Better to
use exactly the same format argument for both packing and unpacking. I
would use '!L' for both, since inet_ntoa and inet_aton are defined to work
with IPv4 addresses in _network_ byte order.
--
Alan Bawden
More information about the Python-list
mailing list