C port scanner terminal output

Simple Port Scanner in C for Penetration Testing

Learn how to write a basic TCP port scanner in C to test open ports on a target system. A great starting point for ethical hacking or network diagnostics.

SecurityTools
Intermediate | 5 min

2025-06-05

Simple Port Scanner in C for Penetration Testing

If you're getting started with ethical hacking or want a deeper understanding of how port scanning works, writing your own port scanner in C is a great way to learn. This guide walks you through building a basic TCP port scanner from scratch.

💡 What Is a Port Scanner?

A port scanner checks which ports on a remote machine are open by attempting to establish TCP connections. Open ports indicate services that may be vulnerable or useful for access.

🛠️ C Port Scanner Code Example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <IP Address>\n", argv[0]);
        return 1;
    }

    int port;
    struct sockaddr_in target;
    target.sin_family = AF_INET;
    target.sin_addr.s_addr = inet_addr(argv[1]);

    printf("Scanning ports on %s...\n", argv[1]);

    for (port = 1; port <= 1024; port++) {
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        target.sin_port = htons(port);

        if (connect(sock, (struct sockaddr *)&target, sizeof(target)) == 0) {
            printf("[+] Port %d is open\n", port);
        }
        close(sock);
    }

    return 0;
}

🔐 Ethical Use Only

Only use port scanners on systems you own or are authorized to test. Unauthorized scanning is illegal in many jurisdictions.

🚀 How to Compile & Run

gcc port_scanner.c -o scanner
./scanner 192.168.1.1

Replace `192.168.1.1` with the IP of your test machine. The scanner will attempt connections on ports 1–1024 and list which ones are open.

📘 What You Learned

  • How TCP port scanning works
  • Basic socket programming in C
  • Safe practices for scanning your own network

This is just a starting point. Advanced scanners like Nmap add features like service detection, UDP scanning, and OS fingerprinting. But knowing how it works under the hood is essential for serious security work.

Download the material

Back to blogs