Home

getpeername

getpeername is a socket API function used to obtain the address of the remote peer to which a socket is connected. It is commonly used with stream sockets such as TCP and with connected datagram sockets to learn the peer’s network endpoint for logging, access control, or response routing.

Signature and parameters: In POSIX systems, int getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen). The function

Address families: The returned address is a sockaddr structure of the appropriate family (AF_INET for IPv4,

When it can fail: The function returns 0 on success and -1 on error, with errno set.

Usage example: After accept() or connect(), call getpeername to retrieve the peer’s address and port, e.g., fill

See also: getsockname to obtain the local address, and getnameinfo to convert binary addresses to text.

writes
the
peer’s
address
into
the
buffer
pointed
to
by
addr
and
stores
the
length
in
addrlen.
On
Windows,
the
signature
is
int
getpeername(SOCKET
s,
struct
sockaddr
*name,
int
*namelen).
The
exact
types
vary,
but
both
forms
fill
a
sockaddr
structure
with
the
peer’s
address;
the
addrlen
parameter
must
initially
contain
the
size
of
the
buffer,
and
on
return
contains
the
actual
length.
AF_INET6
for
IPv6,
AF_UNIX
for
local
sockets).
The
caller
typically
inspects
sa_family
to
select
the
proper
cast
(to
sockaddr_in
or
sockaddr_in6)
and
then
reads
the
address
and
port
fields.
For
readability,
getnameinfo
or
inet_ntop
can
convert
it
to
textual
form.
ENOTCONN
may
be
returned
if
the
socket
is
not
connected;
EBADF
if
the
descriptor
is
invalid;
EINVAL,
ENOBUFS,
or
EFAULT
can
occur
on
some
platforms
for
invalid
arguments
or
buffers.
a
sockaddr_storage,
pass
its
pointer
and
its
length,
then
use
getnameinfo
to
convert
to
a
human-readable
string
for
logging
or
display.