Networking in C · intermediate · ~12 min
Read a working, runnable TCP client that connects to 127.0.0.1, sends a line, reads the echo.
Mirror of the server pattern: 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;
}
alarm() or SO_RCVTIMEO if you want a timeout.Client lifecycle: socket → connect → send/recv → close. Mirror of the server. Both stay on 127.0.0.1.