Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using inet_ntoa function in Python

Tags:

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

like image 964
tibi3384 Avatar asked Mar 07 '11 09:03

tibi3384


1 Answers

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.

like image 185
phihag Avatar answered Oct 17 '22 13:10

phihag