Question

I made a simple C port-scanner program in Linux. The main algorithm is try calling connect, if it returns -1, I was not able to connect, else I connected the host. This works fine in my computer, it lists my open ports. However, in my home there is another computer (behind same router with mine) and I give it's IP but program hangs. I tried google.com, facebook.com or any other website and they do not even respond to first request. What am I doing wrong?

EDIT:

for(port=0; port<=65536; port++)  
{  
    struct sockaddr_in addr;        
    addr.sin_family = AF_INET;  
    addr.sin_port = htons(port);  
    addr.sin_addr = *((struct in_addr *)he->h_addr);  
    memset(&(addr.sin_zero), '\0', 8);  
    if (connect(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) {
        printf("%i closed\n", port);  
        close(sockfd);  
    }  
    else {  
        printf("%i open\n", port);  
        close(sockfd);  
    }  
} 
Était-ce utile?

La solution

By default connect will block for a period before returning an error. You can choose a shorter timeout by setting the socket to non-blocking mode then calling connect then select with a timeout.

There are plenty of examples of this. This tutorial on nonblocking sockets is quite clear. Or see OsNetworkConnect for an example I wrote previously.

Your attempts to connect to arbitrary ports on external sites may be deliberately blocked (by sys admins discouraging port scanners!).

Note also that your loop conditions are slightly out. You should terminate at port 65535. 65536 can't be represented in 16 bits.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top