Skip to content
systemcoding.dev
Networking

Write a TCP Client in C with connect

Write a TCP client in C that calls socket and connect, sends a request, reads the reply until the server closes, and handles errors on Linux.

7 min read
Summarize in AI
Flat illustration of network packets crossing between two hosts, with the C, Linux and Rust logos.

A TCP client is shorter than a server. It creates a socket, calls connect to reach a known address and port, exchanges bytes and closes. This post builds a small client on Linux 6.12 with glibc 2.40 that talks to the echo server from the previous post, explains what connect does on the wire, and lists the errors it can return. A client does not call bind or listen.

The call is documented in the connect(2) man page, and the protocol itself in RFC 9293.

What connect does

When you call connect on a TCP socket, the kernel picks a free local port, chooses a source address from the routing table, and starts the three-way handshake: it sends a SYN, the server answers SYN-ACK, and the kernel replies with ACK. connect returns 0 only after that exchange succeeds. On a blocking socket the call waits for the whole handshake, which is why an unreachable host can stall a program for a long time.

Because the kernel assigns the local port, the client does not need bind. The port is chosen from the ephemeral range, which on Linux is set in net.ipv4.ip_local_port_range.

Building the server address

For a learning client, the address is a text IPv4 string and a port number. inet_pton converts the text into the 4 bytes the structure wants, and htons fixes the port's byte order:

c
struct sockaddr_in server = {0};
server.sin_family = AF_INET;
server.sin_port = htons(7070);
if (inet_pton(AF_INET, "127.0.0.1", &server.sin_addr) != 1) {
    fprintf(stderr, "bad address\n");
    return EXIT_FAILURE;
}

inet_pton returns 1 on success, 0 if the string is not a valid address and -1 if the family is unsupported. Hostnames need getaddrinfo, covered in a separate post.

Connecting and checking the result

c
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) { perror("socket"); return EXIT_FAILURE; }

if (connect(fd, (struct sockaddr *)&server, sizeof server) < 0) {
    perror("connect");
    close(fd);
    return EXIT_FAILURE;
}

If the connection fails, do not retry on the same descriptor. After a failed connect, the state of the socket is unspecified by POSIX, so close it and create a fresh one for the next try.

The errors you will meet most often:

errnoMeaning
ECONNREFUSEDThe host answered but nothing listens on that port; it sent a reset
ETIMEDOUTNo reply arrived before the kernel gave up retransmitting the SYN
ENETUNREACHThe routing table has no route to the network
EHOSTUNREACHThe network is known but the host cannot be reached
EINTRA signal interrupted a blocking connect; do not simply call it again

The last row has a trap. After EINTR the handshake continues in the background, and a second connect call on the same socket fails with EALREADY or EISCONN. The safe approach is to treat it as a failure and start over, or to wait for the socket to become writable with poll.

Sending and reading

Send a request, then read until the server closes or you have all the data. Because send can write fewer bytes than asked, use a loop:

c
static int send_all(int fd, const char *buf, size_t len)
{
    while (len > 0) {
        ssize_t n = send(fd, buf, len, MSG_NOSIGNAL);
        if (n < 0) {
            if (errno == EINTR) continue;
            return -1;
        }
        buf += n;
        len -= (size_t)n;
    }
    return 0;
}

For a request-reply exchange, a client often calls shutdown(fd, SHUT_WR) after sending. That tells the server there is no more input, and the server's recv returns 0. The client can then read until its own recv returns 0.

The complete client

tcp_client.cc
#define _DEFAULT_SOURCE
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

static int send_all(int fd, const char *buf, size_t len)
{
    while (len > 0) {
        ssize_t n = send(fd, buf, len, MSG_NOSIGNAL);
        if (n < 0) {
            if (errno == EINTR) continue;
            return -1;
        }
        buf += n;
        len -= (size_t)n;
    }
    return 0;
}

int main(void)
{
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0) { perror("socket"); return EXIT_FAILURE; }

    struct sockaddr_in server = {0};
    server.sin_family = AF_INET;
    server.sin_port = htons(7070);
    if (inet_pton(AF_INET, "127.0.0.1", &server.sin_addr) != 1) {
        fprintf(stderr, "bad address\n");
        close(fd);
        return EXIT_FAILURE;
    }

    if (connect(fd, (struct sockaddr *)&server, sizeof server) < 0) {
        perror("connect");
        close(fd);
        return EXIT_FAILURE;
    }

    const char *msg = "hello from the client\n";
    if (send_all(fd, msg, strlen(msg)) < 0) {
        perror("send");
        close(fd);
        return EXIT_FAILURE;
    }
    shutdown(fd, SHUT_WR);

    char buf[256];
    for (;;) {
        ssize_t n = recv(fd, buf, sizeof buf, 0);
        if (n < 0) {
            if (errno == EINTR) continue;
            perror("recv");
            break;
        }
        if (n == 0) break;
        fwrite(buf, 1, (size_t)n, stdout);
    }

    close(fd);
    return EXIT_SUCCESS;
}

Compile with gcc -std=c11 -Wall -Wextra -o tcp_client tcp_client.c. With the echo server from the previous post running, the output is:

Text
hello from the client

With no server running, connect fails at once on the loopback interface, because the kernel answers the SYN with a reset:

Text
connect: Connection refused

On a remote host the same failure can instead take a long time and end in ETIMEDOUT, because a dropped SYN produces no answer at all.

Choosing the local address

Sometimes you must control which local address or port the client uses, for example when a host has several interfaces. Call bind before connect with the address you want, or with port 0 to keep the kernel's choice of port. Most clients never need it.

What the handshake looks like from the client

Seeing the handshake makes the error table easier to remember. When your program calls connect, the kernel sends a SYN segment to the server's address and port. Three things can happen next.

If a socket is listening there, the server's kernel answers with SYN-ACK, your kernel sends ACK, and connect returns 0. If the host is reachable but nothing listens on the port, the server's kernel answers with a reset, and connect fails at once with ECONNREFUSED. If a firewall silently drops the SYN, or the host is down, no answer comes. Your kernel then retransmits the SYN several times with growing delays, and only after the retry limit is spent does connect fail with ETIMEDOUT. On Linux the number of attempts comes from net.ipv4.tcp_syn_retries, so the total wait is a matter of system configuration and not a number your program can assume.

This difference matters in practice. A refused connection tells you the machine is alive and the service is down, which is a useful diagnosis. A timeout tells you much less. When you write a client for real use, set a deadline, as covered in the post on non-blocking connect with a timeout, so a dead host cannot hold your program for as long as the kernel's defaults allow.

Reading until the server is done

The read loop in the client stops when recv returns 0, which means the server closed its sending side. That works for a protocol where the server closes after replying. Many protocols do not close, so the client must know when a reply is complete in another way, such as a length prefix or a terminating line. Reading until end of stream is correct only when end of stream is part of the protocol.

Also remember that one recv call can return a partial reply. The echo server sends back the exact bytes it got, but the network may split them differently on the way, so the client may receive the 22 bytes of the message in two or three pieces. The loop above handles that, because it keeps calling recv and writing out each piece until the stream ends. Code that calls recv once and assumes it holds the whole reply works on loopback during testing and fails on a real network.

Trying it against real servers

You can point the same client at any TCP service whose address you know. Change the port and address constants, and send a request that the service understands. A plain-text protocol such as HTTP/1.1 is a good exercise: send a request line, a Host header and a blank line, then read until the server closes. Because the client never sees an encrypted channel here, use it only against services you control or that accept plain-text connections. For the encrypted web you need a TLS library on top of the socket, which is outside this post.

Share

Keep reading

Flat illustration of a microcontroller wired to an LED and a sensor, with the Bluetooth, Nordic Semiconductor and Arm logos.
Embedded

Create a Custom BLE GATT Service on nRF52

Define a custom 128-bit GATT service on nRF52 with Zephyr: characteristic properties, read and write callbacks, notifications through the CCC and MTU limits.

9 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.