recvfrom Function

The recvfrom function receives data from a connectionless socket and stores the data and address of the sender.

Syntax


int recvfrom(
  _In_  SOCKET  s,
  _Out_ char    *buf,
  _In_  int     len,
  _In_  int     flags,
  _Out_ sockaddr* from,
  _Inout_ int*    fromlen
);

                

Parameters

Parameter Description
s A descriptor that identifies a socket.
buf A buffer that receives the data sent by the remote host.
len The size, in bytes, of the buffer pointed to by the buf parameter.
flags Flags that control the behavior of the function call. See the Remarks section for a list of possible values.
from An optional pointer to a buffer that receives the source address of the message. See the sockaddr structure.
fromlen An optional pointer to a buffer that specifies the size of the from buffer. On return, this parameter contains the actual size of the source address.

Return Value

Value Description
Nonnegative The number of bytes received, or the total number of bytes in the datagram for non-blocking sockets.
SOCKET_ERROR A Winsock error has occurred. Use WSAGetLastError to obtain the specific error code.

Remarks

The recvfrom function is used with connectionless sockets (SOCK_DGRAM or SOCK_RAW). For connection-oriented sockets (SOCK_STREAM), use the recv function.

If the underlying transport provider has a-bounded protocol, such as [UDP], the recvfrom function will read as much data as is available, up to the size specified by the len parameter. If the datagram is larger than the buffer, the datagram will be truncated.

If the from parameter is not NULL, and the underlying transport provider supports it, the source socket address of the datagram is copied into the buffer pointed to by the from parameter. The size of the socket address is copied into the integer pointed to by the fromlen parameter.

If no message is available on the socket, and the socket is set to non-blocking mode, recvfrom returns SOCKET_ERROR and WSAGetLastError returns WSAEWOULDBLOCK.

If the socket is set to blocking mode, recvfrom will block until a message is available.

Important Notes:

  • The from and fromlen parameters are required for connectionless sockets. If they are NULL, the function will return SOCKET_ERROR and WSAGetLastError will return WSAEINVAL.
  • The flags parameter can be used to influence the behavior of the socket function. For recvfrom, the following flags are supported:
    • MSG_PEEK: Peek at an incoming message but do not remove it from the input queue.
    • MSG_OOB: Process out-of-band data.
  • For a more detailed explanation of Winsock programming, refer to the Winsock Programming Concepts section.

See Also