I am currently looking into socket programming in python and I am experiencing some strange behavior with socket.htons() … it appears to be flipping the bytes on every call.
I am implementing a simple ping script, as far as I am aware network byte order is big endian and my systems byte order is little endian .
If I use htons on my 16 bit checksum wireshark reports that it is incorrect , however if I just pack the checksum into a struct without using htons wireshark confirms it is correct.
This is what wireshark has captured when using htons
Checksum: 0xece4 [incorrect, should be 0xe4ec]
And here is a quick example…
>>> z = 0xFF00
>>> print z
65280
>>> z = socket.htons(z)
>>> print z
255
>>> z = socket.htons(z)
>>> print z
65280
Any thoughts on this would be greatly appreciated, hopefully its just me doing something very wrong.
Edit:
>>> print sys.byteorder
little
Everything looks to be working like it should. Even in your example, the 2 bytes are being swapped, then back again. If the system byte order is the same as the network, then its a no-op, but your question states that the network bytes order is Big, and the host is Little, so the swapping is what it should be doing.
From the python socket reference: