Monday, December 28, 2009

ntoh and hton

In socket programming, the 'htons' and 'ntohs' usually used for converting the IP port byte order. This can ensure the integer that represent correctly in different endian-ness of the machine.

On some machines, they basically do nothing such as IBM machine. On others, they
rearrange all the bytes ( swap bytes), eg Intel.

Little-endian architecture (eg,Intel) ==> swap bytes
Big-endian architecture (eg, IBM, Motorola) ==> output is same as input

htons() \\host to network short, converts a short from host byte order to network byte order

htonl() \\host to network long

ntohs() \\network to host short

ntohl() \\network to host long


We use 'hton' when we're about to send stuff over the wire, and 'ntoh' to convert the data on the wire into a form we can use. The end output that will travel on the wire is "Network Byte Oder" that represent by "Big Endian"

No comments:

Post a Comment