Home

sockaddrin

sockaddr_in, commonly written as sockaddr_in, is the IPv4 socket address structure used in the BSD sockets API to describe an endpoint for IPv4 communication. It is defined in the header netinet/in.h and is used with socket operations such as bind, connect, sendto, and recvfrom. The generic interface often requires casting to a pointer to struct sockaddr for these functions, which enables IPv4 addresses to be used interchangeably with other address families.

The structure contains several fields:

- sin_family, which must be set to AF_INET to indicate IPv4.

- sin_port, the port number in network byte order; it is typically populated using the htons function.

- sin_addr, a struct in_addr whose s_addr holds the IPv4 address in network byte order; conversion functions

- sin_zero, padding to make the structure the same size as the generic sockaddr; it is usually initialized

Typical usage involves zeroing the structure, setting the family and port, and assigning the address, then passing

sockaddr_in is specific to IPv4, while the generic sockaddr structure serves as a common header for all

such
as
inet_pton
or
inet_addr
are
commonly
used
to
set
this
field.
to
zero.
a
pointer
to
it
cast
to
struct
sockaddr
for
socket
calls.
For
example,
a
server
would
fill
sin_family
with
AF_INET,
sin_port
with
htons(port),
and
sin_addr
with
the
desired
address
(often
INADDR_ANY
to
listen
on
all
interfaces).
address
families.
For
IPv6,
a
parallel
structure,
sockaddr_in6,
is
used.
The
API
remains
largely
consistent
across
platforms,
including
Unix-like
systems
and
Windows,
making
sockaddr_in
a
foundational
element
of
IPv4
networking.