Sockets - Byte Order
- There are two types of byte ordering: big endian and little endian
Byte Ordering
- Integer types (char, short, int, long) can be represented in memory as either big endian or little endian
- Assuming memory addresses increase from left to right, big endian is how you'd write the actual bytes -- with low order bytes in higher memory location
- Little endian is just the opposite, low order bytes would be stored in lower memory locations
- Which end of a multi-byte value (big or little) is stored in the lower memory address
unsigned short = 1; M E M O R Y A D D R E S S ----------------------------> 0x00 0x01 +------------------+------------------+ big endian | high order byte | low order byte | | | | | 0 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 1 | +------------------+------------------+ +------------------+------------------+ little endian | low order byte | high order byte | | | | | 0 0 0 0 0 0 0 1 | 0 0 0 0 0 0 0 0 | +------------------+------------------+
Host Byte Order vs. Network Byte Order
- host byte order - the byte order used by a given system. I.e. Intel x86 processors use little endian.
- network byte order - the byte order used by a network protocol. I.e. IP uses big endian.
- When writing to socket address structures, port #'s (16 bits) and IP addresses (32 bits),
MUST be converted to network byte order
#include <netinet/in.h> /* * HOST => NETWORK */ /* unsigned 16 bit */ uint16_t htons (uint16_t 16bithostvalue); /* unsigned 32 bit */ uint32_t htonl (uint32_t 32bithostvalue); /* * NETWORK => HOST */ /* unsigned 16 bit */ uint16_t ntohs (uint16_t 16bitnetworkvalue); /* unsigned 32 bit */ uint32_t ntohl (uint32_t 32bitnetworkvalue);