Swap 16-bit values between host and network order with htons
Convert a 16-bit port or length to network byte order with htons before it goes on the wire, and back with ntohs. Both come from arpa/inet.h on POSIX.
Network protocols put multi-byte integers in big-endian order, and most machines you will run on are little-endian. A value you copy into a header unconverted arrives byte-swapped, which is how port 8080 turns into 36895. htons converts a 16-bit value from host to network order and ntohs converts it back. On a big-endian host both do nothing, so write them anyway.
#include <arpa/inet.h>
#include <stdint.h>
#include <stdio.h>
int main(void)
{
uint16_t host = 8080; /* 0x1F90 */
uint16_t wire = htons(host);
unsigned char *b = (unsigned char *)&wire;
printf("bytes on the wire: %02x %02x\n", b[0], b[1]);
printf("back again: %u\n", ntohs(wire));
return 0;
}bytes on the wire: 1f 90
back again: 8080The wire bytes are 1f 90 whatever the host, which is the point. Convert at the edges: when you fill a sockaddr_in or a header, and when you read one. Do not convert twice, and do not convert values that are already bytes, such as a MAC address or a payload. Comparing a received port with a constant is cheaper if you convert the constant, because htons(80) on a literal folds at compile time. The functions are specified by POSIX, and htonl and ntohl do the same for 32 bits.