Networking in C · beginner · ~8 min
Convert numbers and addresses between host and network byte order.
Different CPUs store multi-byte integers in different orders ("endianness"). To make networking portable, every multi-byte field in a network packet is stored in network byte order, which is big-endian (most significant byte first).
You convert with:
htons(x) — host to network short — for 16-bit values like a port.htonl(x) — host to network long — for 32-bit values like an IPv4 address.ntohs, ntohl — reverse direction.inet_pton(family, "127.0.0.1", &addr) — parse a dotted-decimal string into an in_addr. Modern, preferred over the deprecated inet_addr.#include <arpa/inet.h>
#include <stdio.h>
int main(void) {
/* port 8080 in network byte order */
unsigned short p = htons(8080);
printf("port bytes: %02x %02x\n", ((unsigned char*)&p)[0], ((unsigned char*)&p)[1]);
struct in_addr a;
inet_pton(AF_INET, "127.0.0.1", &a);
printf("addr bytes: %08x (network order)\n", a.s_addr);
return 0;
}
sin_port = 8080; is wrong; you need sin_port = htons(8080);.inet_addr (returns INADDR_NONE ambiguously when the string IS 255.255.255.255). Use inet_pton instead.Network byte order is big-endian. Use htons/htonl for fields you write into a network packet. Use inet_pton to parse IPs.