5

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

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
tibi3384
  • 53
  • 1
  • 1
  • 3

3 Answers3

14

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.

phihag
  • 278,196
  • 72
  • 453
  • 469
  • I'm using pyjamas for my project and I'm getting: "raise StructError,"argument for i,I,l,L,q,Q,h,H must be integer". I've tried several combinations but nothing seems to work. Is there any workaround to this? – tibi3384 Mar 08 '11 at 13:53
  • @tibi3384 That's probably because you have a string of a number. Wrap it in `int`, like this: `struct.pack('!I', int(string_ip_number_variable))`. – phihag Mar 08 '11 at 14:08
  • Damn,you're right, should have spotted that! Works perfectly. Guess I'm still used to php where the cast would have been performed automatically :). Cheers – tibi3384 Mar 08 '11 at 14:22
  • I strongly dislike python because of things like this. – jrwren Feb 07 '13 at 19:33
  • @jrwren Updated with a current-day solution. I doubt that *any* language offers a simpler way to solve the problem than that. Note that `ntoa` is a socket function and has nothing to do with Python. – phihag Feb 07 '13 at 19:59
2
from struct import pack

n = pack("!I", 167772160)
Kimvais
  • 38,306
  • 16
  • 108
  • 142
0

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.

Paul Hoffman
  • 1,820
  • 3
  • 15
  • 20