0

I want to build a simple port scanner in C++. However, setting the timeout of the socket to 1s, the program waits much longer before testing the next port. Am I doing something wrong?

#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <fstream>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>

int main()
{
    int socketFileDescriptor;
    struct sockaddr_in server_address;

    for (int i=3000; i<65535; i++)
    {
        std::cout<<i<<std::endl;

        socketFileDescriptor = socket(AF_INET,SOCK_STREAM, 0);

        struct timeval tv;
        tv.tv_sec = 1;

        if (setsockopt(socketFileDescriptor, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0)
        {
            perror("Error");
        }

        server_address.sin_family = AF_INET;
        server_address.sin_port = htons(i);
        inet_pton(AF_INET,"212.182.24.27", &(server_address.sin_addr));

        int result = connect(socketFileDescriptor,
                             (struct sockaddr*)&server_address,sizeof(struct sockaddr));
        if (result != -1)
        {
            std::cout<<"Port: "<<i<<std::endl;
        }
        close(socketFileDescriptor);
    }
}
Katie
  • 3,517
  • 11
  • 36
  • 49
  • 2
    I notice you didn't initialize the entire `timeval` structure. You should at least zero out the `tv_usec` value and try again. Either zero-initialize the struct at declaration time before setting `tv_sec`, or explicitly set each member. – paddy Mar 07 '17 at 11:04

1 Answers1

3

SO_RCVTIMEO, as its name should suggest to you, sets a receive timeout, not a connect timeout.

To get a connect timeout, you have to use non-blocking mode and select().

user207421
  • 305,947
  • 44
  • 307
  • 483