Networking in C · intermediate · ~12 min
Read and run a working TCP client. The client connects to `127.0.0.1` (your own machine), sends one line of text, and reads the echo the server sends back.
This client mirrors the server you saw earlier. It follows the same four-step pattern, just from the other side of the connection:
socket -> connect -> send/recv -> close
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
int main(void) {
int fd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in a; memset(&a, 0, sizeof a);
a.sin_family = AF_INET;
a.sin_port = htons(8080);
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (connect(fd, (struct sockaddr *)&a, sizeof a) < 0) { perror("connect"); return 1; }
const char *msg = "hello server\n";
send(fd, msg, strlen(msg), 0);
char buf[256];
ssize_t n = recv(fd, buf, sizeof buf - 1, 0);
if (n > 0) { buf[n] = 0; printf("client got: %s", buf); }
close(fd);
return 0;
}
connect() can block forever. If the server is not running, connect() may wait indefinitely for a response that never comes.alarm() or the SO_RCVTIMEO socket option (SO_RCVTIMEO sets a receive timeout on the socket).socket -> connect -> send/recv -> close.127.0.0.1 (localhost).connect() blocks if the server is not running.