inet_aton and struct issue

David Bear david.bear at asu.edu
Wed Aug 30 19:56:48 EDT 2006


David Bear wrote:

> Diez B. Roggisch wrote:
> 
>> David Bear schrieb:
>>> I found this simple recipe for converting a dotted quad ip address to a
>>> string of a long int.
>>> 
>>> struct.unpack('L',socket.inet_aton(ip))[0]
>>> 
>>> trouble is when I use this, I get
>>> 
>>> struct.error: unpack str size does not match format
>>> 
>>> I thought ip addresses were unsigned 32 bit integers.
>>> 
>>> Is there a better way to take a dotted quad and convert it to a string
>>> representation of an long int?
>> 
>> Works for me:
>> 
>>  >>> import socket
>>  >>> import struct
>>  >>> ip = "127.0.0.1"
>>  >>> struct.unpack('L',socket.inet_aton(ip))[0]
>> 2130706433L
>> 
> 
> I really wish it worked for me:
> 
>>>> struct.unpack('L', socket.inet_aton('129.219.120.129'))
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> struct.error: unpack str size does not match format
> 
> This is python packaged with Suse 9.3.
>>>> dir(struct)
> ['__doc__', '__file__', '__name__', 'calcsize', 'error', 'pack', 'unpack']
>>>> print struct.__file__
> /usr/lib64/python2.4/lib-dynload/struct.so
> 
> could I have a broken python?
> 
>> 
>> Diez
> 
I played around with format size and here are some results. (they don't make
sense)

>>> ip1 = '123.254.254.252'
>>> import socket
>>> import struct
>>> ip1s = socket.inet_aton(ip1)
>>> struct.unpack('L',ip1s)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
struct.error: unpack str size does not match format
>>> struct.unpack('f',ip1s)
(-1.0592039033369304e+37,)
>>> struct.unpack('I',ip1s)
(4244569723L,)
>>> struct.unpack('Q',ip1s)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
struct.error: unpack str size does not match format
>>> struct.unpack('L',ip1s)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
struct.error: unpack str size does not match format
>>> struct.unpack('i',ip1s)
(-50397573,)
>>> struct.unpack('I',ip1s)
(4244569723L,)
>>>

So, ip1s really should be a long unsigned int.. but it doesn't decode as
that. Is this the way to interpret this?

-- 
David Bear
-- let me buy your intellectual property, I want to own your thoughts --



More information about the Python-list mailing list