Binary IP address representation

Philipp Hagemeister phihag at phihag.de
Wed Apr 22 07:27:50 EDT 2009


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512

Hi Dave,

I've solved this now using ipaddr. ipaddr will be in the stdlib as soon
as its developers realize there are actually not one, but two proposals
to fix the remaining issues waiting for their input.

Anyway, since ipaddr:r68, you can do the following:

>>> import ipaddr
>>> ipaddr.IP('::1').packed
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01'

Since you don't know or want to know the family in most use cases, this
interface is actually nicer than that of inet_pton. For the record,
here's how my compatibility function looks like.

def _compat_ipaddr_inet_pton(family, addr):
    if family == socket.AF_INET:
        return ipaddr.IPv4(addr).packed
    elif family == socket.AF_INET6:
        return ipaddr.IPv6(addr).packed
    else:
        raise ValueError("Unknown protocol family " + family)

Since socket.AF_INET6 will not be defined on old systems (are there any
versions of Python 2.5+ that do not have that defined?), your solution
is better for those (but needs netaddr, which is unlikely to enter
stdlib soon). Thanks for sharing it.

Regards,

Philipp

DrKJam wrote:
> Hi,
> 
> I've only just come across this thread this morning :-
> 
> http://mail.python.org/pipermail/python-list/2009-March/703388.html
> 
> Bit late to respond on this list so here is another option (if you are
> still interested).
> 
> Try the netaddr.fallback module :-
> 
>>>> from netaddr.fallback import inet_pton, AF_INET6
>>>> inet_pton(AF_INET6, '::1')
> \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01
> 
> It is self contained and written in pure Python. Forms part of the
> latest 0.6.2 release of netaddr.
> 
> Apologies the code in my project comes across as unreadable :-(
> 
> Regards,
> 
> Dave M.
> 
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEAREKAAYFAknu/zAACgkQ9eq1gvr7CFwUwwCfQLP+dnOdjn9JEttcaFQb5FH0
hLQAn33Lve8k/HXVsW0j7JZP3dL7897W
=ki8e
-----END PGP SIGNATURE-----



More information about the Python-list mailing list