socket module htonl/ntohl bug

David Margrave davidma at
Wed Jun 12 21:50:11 EDT 2002


The following statement should work, but does not, on python 1.5.2 and
python 2.2:

>>> socket.htonl(pow(2L,32)-1)
Traceback (innermost last):
  File "<stdin>", line 1, in ?
OverflowError: long int too long to convert

2^32-1 is a valid 32-bit value, equal to 32 1s in binary, and htonl
should be able to handle it.  This is not related to the argument
being a long int and htonl not accepting that type, because
socket.htonl(4294967295) raises the same exception, and 4294967295 can
be represented as a regular int in python2 (but not 1.5).

By way of comparison, the following simple C program works properly:

#include <stdio.h>
#include <sys/socket.h>

int main(void)
        printf ("%u\n", htonl(4294967295));

When run, it prints out '4294967295' as expected.


More information about the Python-list mailing list