Networking in C · beginner · ~8 min
Build an IPv4 address struct and pass it to `bind()` or `connect()`.
The socket functions accept a generic address pointer: struct sockaddr *.
That type is deliberately vague. It works for many address families. For IPv4 you fill in a more specific struct, struct sockaddr_in, and pass a pointer to it:
struct sockaddr_in {
sa_family_t sin_family; /* AF_INET */
in_port_t sin_port; /* network byte order */
struct in_addr sin_addr; /* IPv4 address */
char sin_zero[8]; /* padding, set to 0 */
};
Before filling any field, zero the whole struct:
memset(&a, 0, sizeof a);
The sin_zero field is padding. Some older code or stricter kernels can read those bytes, so leaving them uninitialized may cause the address to be rejected. Zeroing once keeps the padding clean.
After that, set three fields: family, port, and address.
Two common constants pick which interface you bind to:
INADDR_ANY is 0.0.0.0. It means "listen on every interface," including external ones.INADDR_LOOPBACK is 127.0.0.1. It means "localhost only."In this course we use INADDR_LOOPBACK.
#include <netinet/in.h>
#include <string.h>
struct sockaddr_in a;
memset(&a, 0, sizeof a);
a.sin_family = AF_INET;
a.sin_port = htons(8080); /* see next lesson */
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); /* 127.0.0.1 */
memset it to 0 first.INADDR_ANY when you want localhost only. INADDR_ANY listens on every interface, including external ones. Use INADDR_LOOPBACK to stay local.struct sockaddr_in is the IPv4 address struct.memset, then set sin_family, sin_port, and sin_addr.INADDR_LOOPBACK to bind to localhost; INADDR_ANY listens on every interface.