int -> IP

Klaus Baldermann kbaldermann at entire-systems.com
Tue Nov 30 14:57:40 CET 1999


Andrew M. Kuchling wrote in message
<3dg0y1nimy.fsf at amarok.cnri.reston.va.us>...
>sbarron at twilight. (Scott Barron) writes:
>> The string is a representation of the IP address as a long int in network
>> byte order.  For example 16777343 would be 127.0.0.1.  So it can't be


>def transip2 (ipstr):
>    # Pack into a 4-byte integer
>    s = struct.pack('!L', string.atol(ipstr) )
>
>    # Unpack as 4 bytes
>    L = struct.unpack('!4B', s)
>
>    return `L[3]`+'.' + `L[2]`+'.'+`L[1]`+'.'+`L[0]`

PMFJI a bit late, but the last line looks a bit tedious to type :-)
packing it the other direction (little endian) enables us using string.join:

>>> from struct import pack, unpack
>>> from string import atol, join
>>> def transip3(long): return join(map(str,unpack('4B', pack('<L',
atol(long)))), '.')

>>> transip3('16777343')
'127.0.0.1'
>>> transip3('2227275982')
'206.136.193.132'
>>>

map-filter-and-reduce-remind-me-of-APL-ly yours
Klaus







More information about the Python-list mailing list