Network Byte Order

  • We need to know two of the basic data types in C language:
    • char: smallest data type. Its size is at least 8 bits
    • integer:
  • Each basic data type (aka Arithmetic type specifier) can be further classified with one of these optional specifiers:
    • Short
    • Long
    • Signed
    • Unsigned

for example, a type of Integer can be:

    • Short Unsigned Int: written on 16 bits
    • Short Signed Int: written on 16 bits
    • Long Unsigned Int: written on 32 bits
    • Long Signed Int: written on 32 bits
  • For computers to communicate, they need to have the same endianness. Each computer has its own Host Byte Order, which is how they represent multibyte words in memory..
    • x86 processors are Little Endians. ARM processors (such as in Iphone) are Big Endians)
  • The way network protocols represent multibyte words is called Network Byte Order. They use the Big Endian format. But what if the computer processor Host Byte Order is Little Endian and the computer wants to write data to the network?
    • the computer can use specific network libraries (or functions) that convert multibyte words from one format to another. They are:
      • htons(): Host to Network Short: converts a multibyte word unsigned short integer from Host Byte Order to the Network Byte Order
      • htonl(): Host to Network Long: converts an unsigned long integer multi byte word from Host Byte Order to Network Byte Order
      • ntohs(): Network to Host Short: converts an unsigned ¬†short integer multi byte word from Network Byte Order to Host Byte Order
      • ntohl(): Network to Host Long: converts an unsigned ¬†long integer multi byte word from Network Byte Order to Host Byte Order.
  • When called, these functions behave differently on Little Endian machines and Big Endian machines:
  • on Little Endian machines, calling them invokes a transformation of the multibyte word (Network Byte Order to Host Byte Order and vice-versa, depending on the function)
  • on Big Endian machines, calling them transforms nothing. They become nulled functions.

 

References

Wikipedia: C Data Types

Leave a Comment