cybersecurity · intermediate · ~15 min · safe pentest lab

Localhost-only TCP connection checker

Practise hard-coded scope limits as a defensive guarantee.

Challenge

Implement int check_local(const char *host, int port) that:

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

This is the canonical defensive shape of a local-only tool: the policy check is the first line of code.

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.