Networking in C · intermediate · ~12 min

A complete simple TCP client (localhost)

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.

Lesson

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

  • socket creates the endpoint.
  • connect reaches out to the server's address and port.
  • send / recv exchange data over the open connection.
  • close releases the socket when you are done.

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

  • connect() can block forever. If the server is not running, connect() may wait indefinitely for a response that never comes.
    • To set a time limit, use alarm() or the SO_RCVTIMEO socket option (SO_RCVTIMEO sets a receive timeout on the socket).

Summary

  • A TCP client follows the lifecycle: socket -> connect -> send/recv -> close.
  • This is the mirror image of the server pattern.
  • Both client and server in this lesson stay on 127.0.0.1 (localhost).
  • Watch out: connect() blocks if the server is not running.

Practice with these exercises