Home

getsockname

getsockname is a networking function that retrieves the local address to which a socket is bound, or the address it would be bound to if the socket is not yet bound. It applies to sockets using IPv4, IPv6, and Unix domain sockets, and is commonly used to discover the local endpoint of a connection or to determine which local address the system would use for binding.

In POSIX systems, the prototype is typically int getsockname(int sockfd, struct sockaddr *name, socklen_t *addrlen). On

Return value is zero on success and -1 on error in POSIX, with errno set to indicate

Behavior notes: if the socket is already bound, getsockname returns the local address and port bound to

The result is returned in a sockaddr structure; the sa_family field identifies the family, and the data

See also: getpeername, bind, connect.

Windows,
the
function
uses
a
SOCKET
handle
and
an
int*
for
addrlen,
with
a
result
of
SOCKET_ERROR
on
failure.
The
parameters
are:
sockfd
(or
the
equivalent
socket
handle)
identifying
an
open
socket;
name,
a
buffer
into
which
the
local
address
is
written;
and
addrlen,
an
input/output
value
that
initially
specifies
the
size
of
the
buffer
and
on
return
holds
the
actual
length
of
the
address.
the
error.
In
Windows,
a
return
value
of
0
indicates
success,
while
a
return
value
of
SOCKET_ERROR
indicates
failure
and
WSAGetLastError
provides
the
error
code.
the
socket.
If
the
socket
is
not
bound,
it
may
return
the
address
that
would
be
used
for
binding,
often
an
unspecified
local
address
and
port
(for
example,
INADDR_ANY
with
port
0
in
IPv4).
For
Unix
domain
sockets,
the
address
will
include
the
filesystem
path.
can
be
interpreted
via
the
appropriate
sockaddr_in,
sockaddr_in6,
or
sockaddr_un
structures.