Building a TCP Client
A TCP client reaches out and starts a conversation with a server. Five beats: create a socket, connect, send, receive, close.
The Complete Client
#include <stdio.h>#include <string.h>#include <unistd.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>
int main() { // 1. Create socket int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("socket"); return 1; }
// 2. Set up server address struct sockaddr_in server_addr; memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(8080); if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) != 1) { fprintf(stderr, "bad address\n"); close(sockfd); return 1; }
// 3. Connect if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { perror("connect"); close(sockfd); return 1; }
// 4. Send data const char *msg = "Hello, server!"; send(sockfd, msg, strlen(msg), 0);
// 5. Receive response char buffer[1024]; ssize_t bytes = recv(sockfd, buffer, sizeof(buffer) - 1, 0); if (bytes > 0) { buffer[bytes] = '\0'; printf("Server says: %s\n", buffer); }
// 6. Close close(sockfd); return 0;}Error Handling Patterns
Every socket call can fail. C's answer is the same as everywhere else — check the return value:
if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("connect"); // prints "connect: Connection refused" etc. close(sockfd); return 1;}perror() reads the global errno variable and prints a human-readable error message. Always call it immediately after a failed system call, before any other function has a chance to change errno.
Reading Until Done
recv() doesn't promise to hand you everything in one go. Real code loops, here until the buffer is full or the server closes the connection:
size_t total = 0;while (total < sizeof(buffer) - 1) { ssize_t bytes = recv(sockfd, buffer + total, sizeof(buffer) - total - 1, 0); if (bytes < 0) { perror("recv"); break; } // error if (bytes == 0) break; // peer closed the connection total += (size_t)bytes;}buffer[total] = '\0';The runner has no network, but a socketpair gives you two connected sockets inside one machine, and fork puts a pretend server on the other end. The server sends its reply in three separate writes with pauses in between. Predict what a single recv would get, then run it.
On a real network the split points are decided by TCP segments, buffers and timing, not by how the sender happened to call send. You can't predict them, so you loop.
Here's one plausible run with a bigger message: the server makes a single send of 4,000 bytes and the client, with char buffer[4096], runs the loop above. The split shown is illustrative: 1,448 bytes is a typical TCP payload per segment on Ethernet with timestamps on, but recv may just as well return one segment, several merged, or part of one.
One send of 4,000 bytes, three recv calls
Accumulating data in a loop like that shows up in every networking stack you'll ever touch. The wire hands you fragments. Stitching them back together is on you.
DNS Resolution
To connect to a hostname instead of an IP, use getaddrinfo():
#include <netdb.h>
struct addrinfo hints, *result, *rp;memset(&hints, 0, sizeof(hints));hints.ai_family = AF_UNSPEC; // IPv4 or IPv6, whichever workshints.ai_socktype = SOCK_STREAM;
int rc = getaddrinfo("example.com", "80", &hints, &result);if (rc != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rc)); return 1;}
int sockfd = -1;for (rp = result; rp != NULL; rp = rp->ai_next) { sockfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (sockfd < 0) continue; if (connect(sockfd, rp->ai_addr, rp->ai_addrlen) == 0) break; // success close(sockfd); sockfd = -1;}freeaddrinfo(result);
if (sockfd < 0) { fprintf(stderr, "could not connect\n"); return 1;}getaddrinfo() is the modern, protocol-agnostic hostname resolver. A name often maps to several addresses (IPv6 and IPv4, or several servers), and the first one isn't guaranteed to answer, so you try each in turn. It reports errors through its return value rather than errno, which is why you pass that to gai_strerror instead of calling perror. Always pair it with freeaddrinfo() — the result list is heap-allocated.