The companion to the sendto(2) function is the recvfrom(2) function. This function differs from the read(2) function in that it allows you to receive the sender's address at the same time you receive your datagram. The function synopsis is as follows:
int recvfrom(int s,
struct sockaddr *from,
The list of arguments is very similar to those used in the sendto(2) function. The recvfrom (2) arguments are
- The socket s to receive the datagram from.
- The buffer pointer buf to start receiving the datagram into.
- The maximum length (len) in bytes of the receiving buffer buf.
- Option flag bits flags.
- The pointer to the receiving socket address buffer, which will receive the sender's address (pointer argument from).
- The pointer to the maximum length (fromlen) in bytes of the receiving socket address buffer from. Note that the integer that this pointer points to must be initialized to the maximum size of the receiving address structure from, prior to calling the function.
Like any normal read(2) operation, the receiving buffer buf must be large enough to receive the incoming datagram. The maximum length is indicated to the function by the argument len.
The function returns the value -1 if there was an error, and you should consult the value of errno for the cause of the error. Otherwise, the function returns the number of bytes that were received into your receiving buffer buf. This will be the size of your datagram received.
Note especially, however, that the last argument is a pointer to the length of the receiving address structure. Prior to calling the function recvfrom(2), the int value that this pointer points to must contain the maximum byte size of the receiving address structure from. Upon return from the function, the actual size of the address returned is placed into this int variable. In effect, the value pointed to by fromlen acts as both an input value and a returned value.
If you are using the function recvfrom(2) to receive datagrams for varying protocols, make certain that you allow sufficient socket address space to receive all address families that you might encounter. For example, the socket address size differs for address families AF_INET and AF_LOCAL (AF_UNIX). Often a C union data type can allow for the maximum size needed.
There are different flag values available for the recvfrom(2) function, which are listed in Table below,
Processes out-of-band data
Reads a datagram without actually removing it from the kernel's receive queue.
Requests that the operation block until the full request has been
satisfied (with some exceptions)
Receives a packet from the error
Turns off the raising of SIGPIPE for stream sockets when the other end has become disconnected