shaddyshad
shaddyshad

Reputation: 217

Htons byte order conversion

Am new to socket programming and I came up to this Network Byte Conversion mechanisms the htons and the htonl methods.
The documentations said that they convert either a 16-bit or a 32-bit network number from a host network byte order to an Internet byte order.

What happens when the host and network share the same order?
And how do you determine whether you should use them or not?

Upvotes: 0

Views: 1332

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 597101

Network Byte Order is big-endian. The hton...() and ntoh...() functions are effectively no-ops on a big-endian machine, and they swap bytes on a little-endian machine. If the network protocol you are implementing transmits numbers in network byte order, you should always call the functions regardless of platform. That way, all outgoing numbers are guaranteed to be converted from local endian to big-endian, and all incoming numbers are guaranteed to be converted from big-endian to local endian.

Upvotes: 2

Ed Heal
Ed Heal

Reputation: 60017

They may do nothing if it is in the same order. If the other way around it will swap it. Always use them for transport. Both ends will understand

Upvotes: 3

Related Questions