Skip to content

recv() / send()

Purpose

recv() and send() receive and transmit data on connected sockets.

They are similar to read() and write(), but provide socket-specific flags.

#include <sys/types.h>
#include <sys/socket.h>

Prototype

ssize_t recv(int sockfd, void *buf, size_t len, int flags);
ssize_t send(int sockfd, const void *buf, size_t len, int flags);

Minimal Example

ssize_t n = recv(client_fd, buf, sizeof(buf), 0);
if (n == 0) {
    /* Peer closed the connection. */
} else if (n < 0) {
    perror("recv");
}

Common Pitfalls

  • Assuming TCP preserves message boundaries.
  • Not handling partial sends.
  • Not handling EAGAIN / EWOULDBLOCK in non-blocking mode.
  • Treating recv() == 0 as a normal data packet.