Networking in C · beginner · ~8 min
Convert numbers and addresses between host byte order and network byte order.
A multi-byte integer can be stored in memory in more than one order. This ordering is called endianness.
Different CPUs make different choices. The same number can sit in memory in different byte orders on different machines.
To keep networking portable across machines, the standard fixes one order for the wire. Every multi-byte field in a network packet is stored in network byte order, which is big-endian (most significant byte first).
Before you send a number, convert it from your machine's order (the host order) to network order. After you receive one, convert it back.
htons(x) — host to network short — for 16-bit values, such as a port.htonl(x) — host to network long — for 32-bit values, such as an IPv4 address.ntohs, ntohl — the reverse direction (network to host).inet_pton(family, "127.0.0.1", &addr) parses a dotted-decimal string into an in_addr structure. It is the modern function and is 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. It returns INADDR_NONE in an ambiguous way: that value is also the legitimate result for the string 255.255.255.255, so you cannot tell success from failure. Use inet_pton instead.htons/htonl for fields you write into a network packet, and ntohs/ntohl to read them back.inet_pton to parse IP address strings; avoid the deprecated inet_addr.