[Python-Dev] Re: _socket efficiencies ideas

David Bolen db3l@fitlinxx.com
09 Apr 2003 18:11:10 -0400


Neil Schemenauer <nas@python.ca> writes:

> Marcus Mendenhall wrote:
> > Even though cpu time is cheap, we should save it for useful work.
> 
> Saving a few cycles while having the complicate the interface is not the
> Python way.  +1 on restoring the old sscanf code (or something similar
> to it).

For what it's worth, whenever I had network code that I wanted to
accept names or addresses, I always distinguished them through an
attempt using the platform inet_addr() system call.  If that returns
an error (-1), then I go ahead and process it as a name, otherwise I
use the address it returns.

inet_addr() will itself take care of validating that the address is
legal (e.g., no octet over 255 and only up to 4 octets), padding
values as necessary (e.g., x.y.z is processed as if z was a 16-bit
value, x.z as if z was a 24-bit value, x as a 32-bit value), and
permits decimal, octal or hexadecimal forms of the individual octets.
I believe this behavior is portable and well defined.

If you wanted the same code to work for IPv4 and IPv6, you'd probably
want to use inet_pton() instead since inet_addr() only does IPv4,
although that would lose the hex/octal options.  You'd probably have
to conditionalize that anyway since it might not be available on IPv4
only configurations, so I could see using inet_addr() for IPv4 and
inet_pton() for IPv6.

> ObTrivia: IP addresses can be written as a single number (at least for
> many IP implementations).  Try "ping 2130706433".

That's part of the inet_addr() definition.  When a single value is
given as the string, it is assumed to be the complete 32-bit address
value, and is stored directly without any byte rearrangement.

So, 2130706433 is (127*2^24) + 1, or "127.0.0.1" - but then obviously
you knew that :-)

-- David