0

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?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
shaddyshad
  • 217
  • 4
  • 15

2 Answers2

3

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

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
2

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    is it possible to check the `endianness` of your host? And if yeah, how do you do that, and is it even necessary to know – shaddyshad Oct 25 '16 at 04:32
  • @void_shad it is technically possible (and plenty of code examples are floating around for that), but it is not necessary in this situation and doesn't really gain you anything. All local processing should be done using local endian, whatever it happens to be. The compiler takes care of that for you. Only convert endian during transmission/reception, and that is where the conversion functions come into play. If both parties play by these rules, a value of 12345 will still be 12345 on the other end even if both parties are using different platform endians. – Remy Lebeau Oct 25 '16 at 05:51