Networking in C · beginner · ~8 min

struct sockaddr_in — addresses for IPv4

Build an IPv4 address struct to pass to bind() or connect().

Lesson

The socket APIs take a generic struct sockaddr *, but for IPv4 you fill in the more specific struct sockaddr_in:

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  */
};

Always zero-init the whole struct (memset(&a, 0, sizeof a);) — old code or buggy kernels can read the padding. Then fill in family, port, and address.

INADDR_ANY is 0.0.0.0 — "listen on every interface." INADDR_LOOPBACK is 127.0.0.1 — "localhost only." For this course we use INADDR_LOOPBACK.

Code examples

#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 */

Common mistakes

  • Forgetting to zero the struct. Random padding bytes can be rejected by stricter kernels.
  • Using INADDR_ANY when you really want localhost-only. INADDR_ANY listens on every interface, including external ones.

Summary

sockaddr_in is the IPv4 address struct. Zero it, set family/port/addr. Use INADDR_LOOPBACK to bind to localhost.

Practice with these exercises