Search code examples
cport-scanning

how to make my portscan get decent results?


I'm developing a basic portscan using c language. I think my program is working, because it is showing open ports of my IP. But something strange is happening when I execute the program: It gets diferent results everytime:

ex:

wholetomy@wholetomy:~/Desktop$ ./portscan 192.168.0.2
Porta 80 - status [ABERTA] 
Porta 34294 - status [ABERTA] 
Porta 38586 - status [ABERTA] 
Porta 55424 - status [ABERTA] 
wholetomy@wholetomy:~/Desktop$ ./portscan 192.168.0.2
Porta 80 - status [ABERTA] 

the second time that I execute the program, it is showing just port 80, so what is happening with my program, can anyone explain please?

the portscan:

#include <stdio.h>        // printf(), perror()
#include <sys/types.h>    // AF_INET, SOCK_STREAM
#include <sys/socket.h>   // socket(), connect()
#include <netinet/in.h>   // struct sockaddr_in
#include <arpa/inet.h>    // htons(), inet_addr()
#include <unistd.h>       // close()

    int main(int argc, char *argv[])
    {
        int meusocket;
        int conecta;

        int port;
        int inicio = 0;
        int final = 65535;
        char * destino;

        destino = argv[1];

        struct sockaddr_in alvo;
        for(port = inicio; port < final; port++)
        {
        meusocket = socket(AF_INET, SOCK_STREAM, 0);
        alvo.sin_family = AF_INET;
        alvo.sin_port = htons(port);
        alvo.sin_addr.s_addr = inet_addr(destino);

        conecta = connect(meusocket, (struct sockaddr *)&alvo, sizeof alvo);

        if(conecta == 0)
        {
            printf("Porta %d - status [ABERTA] \n",port);
            close(meusocket);
            close(conecta);
        }else{
            close(meusocket);
            close(conecta);
        }
        }
    }

Solution

  • try multithreading, and try to look through the source code of the networking stack in operating systems, you never know, you could make a good exploit engine