Networking in C · advanced · ~10 min

Localhost port checking

Detect which loopback (local) ports accept a TCP connection.

Lesson

How a port scan works

A "scan" is simple: it tries to connect() to each port, one at a time.

  • If the connection succeeds, something is listening on that port.
  • If the connection is refused (ECONNREFUSED), nothing is listening there.

That is the whole idea. You learn what is running by seeing which connection attempts go through.

Keep it strictly local

Scanning hosts you do not own is risky, and not just technically.

Scanning third-party hosts without explicit, written authorisation counts as unauthorised access in many jurisdictions. In other words, it can be illegal.

The platform's exercises only ever target 127.0.0.1 (the loopback address, which always points back to your own machine). They run against test servers ("fixtures") that the exercise harness opens itself.

Common mistakes

  • Reusing the same socket for every attempt. A socket file descriptor (the integer handle the OS gives you for a connection) is single-use here. Open a new socket for each port you test.

Practice with these exercises