Networking in C · intermediate · ~12 min

A complete simple TCP client (localhost)

Read a working, runnable TCP client that connects to 127.0.0.1, sends a line, reads the echo.

Lesson

Mirror of the server pattern: socket → connect → send/recv → close.

Code examples

#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;
}

Common mistakes

  • Forgetting that connect() blocks indefinitely if the server isn't running. Use alarm() or SO_RCVTIMEO if you want a timeout.

Summary

Client lifecycle: socket → connect → send/recv → close. Mirror of the server. Both stay on 127.0.0.1.

Practice with these exercises