Search code examples
clinuxsocketsport-scanning

Random port connection while portscan


I've made a very basic port-scan program in C to scan a port range. Here it is:

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

#define HOST "127.0.0.1"
#define PORT 4444

int createConnection(const char *host[], const int port)
{
    struct sockaddr_in addr;
    int sock = 0;
    int ret;
    struct sockaddr_in server_addr;
    if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    {
        printf("Error %d socket creating.\n", sock);
        return -1;
    }
    else
    {
        memset(&server_addr, '0', sizeof(server_addr));

        server_addr.sin_family = AF_INET;
        server_addr.sin_port = htons(port);
        ret = inet_pton(AF_INET, host, &server_addr.sin_addr);
        if (ret <= 0)
        {
            printf("Error %d unsuported address: %d\n", ret);
            return -2;
        }
        else
        {
            ret = connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr));
            if (ret < 0)
            {
                //printf("[-] Port %d closed.\n", port);
                close(sock);
                return 1;
            }
            else
            {
                printf("[+] Port %d open.\n", port);
                close(sock);
                return 0;
            }
        }

    }
}

int main(int argc, const char *argv[])
{
    for (int i = 1; i < 65536; i++)
    {
        createConnection("127.0.0.1", i);
    }
}

As you can see in the for loop, it scans from port 1 to port 65535. The problem is that when I start it, I get this output:

[+] Port 42178 open.
[+] Port 48650 open.
[+] Port 60078 open.

The "open ports" always change, but are always superior to 40000. But, I checked with netstat -tulpn, only my port 68 is open for the dhclient, which is UDP and not TCP. Why does it say that I have open ports ?


Solution

  • I suspect you're running into your open socket source ports while scanning.

    TCP connections have a source port. If one is not assigned to a socket (via bind), then the kernel assigns an ephemeral port (in the high range) to the socket when you call connect, before the SYN is sent.

    Since you are connecting your sockets to your local machine, as you loop through the destination ports, it is possible that the kernel will assign a random ephemeral source port that happens to match the same destination port to which you're about to connect.

    See: