networking · beginner · ~10 min · safe pentest lab

Connect from a TCP client to a listener

Build a sockaddr_in and call connect() on it.

Challenge

The client side of TCP is three steps: create a socket, fill in the server address, and connect. Wrap that into one helper that connects to a listener on loopback.

Task

Implement int connect_local(int port) that opens a TCP socket and connects to 127.0.0.1:port.

Input

One int port — the loopback port to connect to.

Output

Returns the connected file descriptor on success, or -1 on any failure (for example, nothing is listening on that port).

Example

connect_local(port_with_a_listener)   ->   fd >= 0
connect_local(1)                       ->   -1   (port 1: connection refused)

Edge cases

  • No listener on the port: connect fails (ECONNREFUSED); return -1.
  • Close the socket on any error path so it is not leaked.

Rules

  • Connect to INADDR_LOOPBACK (127.0.0.1) only.

Why this matters

The full client prologue: socket → fill sockaddr_in → connect.

Input format

One integer port to connect to on 127.0.0.1.

Output format

The connected fd on success, -1 on any failure.

Constraints

Connect to INADDR_LOOPBACK only. Close the socket on any error path.

Starter code

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
int connect_local(int port) {
    /* TODO */
    return -1;
}

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.