networking · beginner · ~10 min · safe pentest lab
Build a sockaddr_in and call connect() on it.
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.
Implement int connect_local(int port) that opens a TCP socket and connects to 127.0.0.1:port.
One int port — the loopback port to connect to.
Returns the connected file descriptor on success, or -1 on any failure (for example, nothing is listening on that port).
connect_local(port_with_a_listener) -> fd >= 0
connect_local(1) -> -1 (port 1: connection refused)
connect fails (ECONNREFUSED); return -1.INADDR_LOOPBACK (127.0.0.1) only.The full client prologue: socket → fill sockaddr_in → connect.
One integer port to connect to on 127.0.0.1.
The connected fd on success, -1 on any failure.
Connect to INADDR_LOOPBACK only. Close the socket on any error path.
#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;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.