setsockopt在C ++中不起作用(超时设置为1秒,等待时间更长)

时间:2017-03-07 11:00:33

标签: c++ sockets

我想用C ++构建一个简单的端口扫描程序。但是,将套接字的超时设置为1秒,程序会在测试下一个端口之前等待更长时间。我做错了吗?

#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);
    }
}

1 个答案:

答案 0 :(得分:3)

SO_RCVTIMEO,正如其名称应该建议的那样,设置接收超时,而不是连接超时。

要获得连接超时,您必须使用非阻止模式和select()