gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:56:17 25 4
gpt4 key购买 nike

<分区>

我想用 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);
}
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com