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.
Header¶
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/EWOULDBLOCKin non-blocking mode. - Treating
recv() == 0as a normal data packet.