Sending and receiving over sockets
What you'll learn: How to exchange data between two connected programs using the send() and recv() functions.
The Post Office Analogy
Imagine you have successfully built a "pipe" between two computers. Now, you need to push mail through it. In C, you don't just dump data into a socket and hope for the best. You use two specific tools: send() to push bytes out, and recv() to pull bytes in.
Think of a socket like a small mail slot. You can't shove a whole piano through it at once. If you have a large message, you might have to send it in smaller chunks, and the person on the other side must wait at the slot to collect those pieces as they arrive.
Using send() and recv()
Both functions require three main ingredients: the socket file descriptor (the ID of your connection), a buffer (the actual data), and the length of that data.
One critical thing to remember: sockets work with bytes. If you want to send a string, you are actually sending a sequence of characters.
#include <sys/socket.h>
#include <string.h>
#include <stdio.h>
// Example: Sending and receiving a simple message
void communicate(int socket_fd) {
const char *msg = "Hello, Server!";
char buffer[1024];
// 1. Sending data
// We pass the socket, the string, its length, and a '0' for default flags
int bytes_sent = send(socket_fd, msg, strlen(msg), 0);
if (bytes_sent == -1) {
perror("Send failed");
}
// 2. Receiving data
// We provide a buffer to hold the incoming mail
int bytes_received = recv(socket_fd, buffer, sizeof(buffer) - 1, 0);
if (bytes_received > 0) {
buffer[bytes_received] = '\0'; // Null-terminate the string
printf("Received: %s\n", buffer);
}
}
The "Partial" Problem
In networking, send() and recv() are not guaranteed to handle your entire message in one go. If you try to send 10,000 bytes, the operating system might only send 2,000 and tell you, "I'll handle the rest later."
The return value of these functions tells you exactly how many bytes were actually processed. A professional C programmer always checks these numbers to ensure no data is left behind in the "mail slot."
Key takeaway
Use send() to push byte arrays out and recv() to pull them in, always checking the return value to see how much data actually moved.