Home

recvfrom

recvfrom is a function in the Berkeley sockets API used to receive data from a socket, with the ability to obtain the address of the sender. It is especially common for datagram sockets (UDP) where knowing the source is essential for responding or logging, but it can be used with other socket types as well. The function fills a user-provided buffer with incoming data and, if requested, stores the sender's address in a separate buffer.

In POSIX systems, the typical prototype is ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags, struct

Return value is the number of bytes received, or -1 (or SOCKET_ERROR on Windows) on error. In

Compared with recv, recvfrom adds the ability to capture the sender’s address, which is particularly useful

sockaddr
*src_addr,
socklen_t
*addrlen).
Windows
uses
a
similar
form
with
different
types
and
return
conventions.
The
parameters
are:
sockfd,
the
socket
descriptor;
buf,
the
buffer
to
receive
data;
len,
the
maximum
number
of
bytes
to
read;
flags,
controlling
behavior
(for
example,
MSG_PEEK
to
peek
at
data
without
removing
it);
src_addr,
an
optional
buffer
to
receive
the
sender’s
address;
and
addrlen,
a
pointer
to
a
socklen_t
that
should
initially
hold
the
size
of
the
buffer
pointed
to
by
src_addr
and,
on
return,
hold
the
actual
length
of
the
address.
blocking
mode,
the
call
waits
for
data;
in
non-blocking
mode,
it
may
return
-1
with
EAGAIN
or
EWOULDBLOCK
if
no
data
is
available.
If
src_addr
is
non-NULL,
the
function
writes
the
sender’s
address
(up
to
the
length
specified
by
addrlen).
If
the
socket
is
connected,
the
behavior
of
src_addr
may
reflect
the
connected
peer,
or
be
unused
depending
on
implementation.
for
UDP
servers
and
similar
applications.