cybersecurity · intermediate · ~15 min · safe pentest lab

Localhost-only TCP connection checker

Practise hard-coded scope limits as a defensive guarantee.

Challenge

Build a connection checker that is hard-wired to refuse any target other than loopback. The scope check is the first line of code, so the tool is structurally incapable of touching third-party hosts.

Task

Implement int check_local(const char *host, int port) that attempts a TCP connection only to 127.0.0.1.

Input

  • host: the target host string. Must equal exactly "127.0.0.1" to be accepted.
  • port: the TCP port to connect to. The harness opens a loopback listener and passes its port.

Output

Returns int:

  • -2 if host is not exactly "127.0.0.1" (refused — non-localhost).
  • 1 if a TCP connection to 127.0.0.1:port succeeds.
  • 0 if the connection is refused or otherwise fails.

Example

check_local("127.0.0.1", <open port>)     ->   1
check_local("127.0.0.1", <closed port>)   ->   0
check_local("8.8.8.8", <any port>)        ->   -2   (refused)

Edge cases

  • A NULL host is refused (-2).
  • Any host string other than "127.0.0.1" is refused before any socket is opened.

Rules

  • Check the host policy before opening a socket — refuse first, connect second.

Input format

A host string host and a TCP port.

Output format

-2 if host isn't 127.0.0.1; 1 if the connection succeeds; 0 if it fails.

Constraints

Loopback only — refuse any non-127.0.0.1 host before opening a socket.

Starter code

#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

int check_local(const char *host, int port) {
    /* TODO */
    return -1;
}

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