Skip to content Skip to sidebar Skip to footer

Using Inet_ntoa Function In Python

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 address

Solution 1:

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

importipaddressaddr= str(ipaddress.ip_address(167772160))
assertaddr== '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.

Solution 2:

fromstruct import pack

n = pack("!I", 167772160)

Solution 3:

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.

Post a Comment for "Using Inet_ntoa Function In Python"