5
votes

I've recently started to program in python and I'm having some trouble understanding how inet_nota and inet_aton work in Python. Coming from php/mysql I've always stored ip addresses in the database as long variables. Also the inet_ntoa method in mysql receives a long variable as parameter and returns the dotted format of an IP, so I assumed the Python version works in a similar manner. However, it seems Python's inet_ntoa needs a 32-bit packed binary format. So, having the IP address stored as 167772160 value, how can I convert it to a 32-bit packed binary value (like \x7f\x00\x00\x01) which is needed by inet_ntoa method?

Thanks a lot

3

3 Answers

14
votes

In Python 3.3+ (or with this backport for 2.6 and 2.7), you can simply use ipaddress:

import ipaddress
addr = str(ipaddress.ip_address(167772160))
assert addr == '10.0.0.0'

Alternatively, you can manually pack the value

import socket,struct
packed_value = struct.pack('!I', 167772160)
addr = socket.inet_ntoa(packed_value)
assert addr == '10.0.0.0'

You might also be interested in inet_pton.

2
votes
from struct import pack

n = pack("!I", 167772160)
0
votes

As a late addition to this thread: if you're using Python 3.3 or above, look at the ipaddress module: it's much more functional than the socket equivalents.