C++ 快速检测某个IP以及端口是否可达

因为项目需要,需要快速知道某个IP和端口是否可达(一秒内),用过connect,这个函数会有几秒的时间的检测,不太符合我的需求,大家还有什么别的解决办法吗?

setsockopt函数可以设定socket连接、接收和发送等的响应时间,可以通过在connect之前设置SO_SNDTIMO来达到控制连接超时的目的。
#include

#include

#include

#include

#include

#include

#include

#include

#include

int main(int argc, char *argv[])

{

int fd;

struct sockaddr_in addr;

struct timeval timeo = {3, 0};

socklen_t len = sizeof(timeo);

     fd = socket(AF_INET, SOCK_STREAM, 0);  
     if (argc == 4)  
             timeo.tv_sec = atoi(argv[3]);  

     setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeo, len);  
     addr.sin_family = AF_INET;  
     addr.sin_addr.s_addr = inet_addr(argv[1]);  
     addr.sin_port = htons(atoi(argv[2]));  

    if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {  
            if (errno == EINPROGRESS) {  
                    fprintf(stderr, "timeout/n");  
                    return -1;  
            }         
            perror("connect");  
            return 0;  
    }         
    printf("connected/n");  

    return 0;  

}

使用 ./cmd ip地址 端口 超时秒数

(测试的ip和端口必须是不存在的,或者是ip的机器是死掉的,才会出现,否则机器存在而端口不存在会立即返回的)
可以通过查看errno来查看错误类型来确定无法连接的原因。

发送TCP SYN包,这个会比connect时间端。就是需要自己底层构造数据包

socket可以设置超时时间,把超时时间设置短一点应该就能满足你的要求!

udp也行,弄个定时器多发几次,到时间没收到,就认为超时

connect可以说使用select设置超时

在此,谢谢各位的回答。。。。。