Linux下connect超时处理【总结】

1、前言

  最近在写一个测试工具,要求快速的高效率的扫描出各个服务器开放了哪些端口。当时想了一下,ping只能检测ip,判断服务器的网络是连通的,而不能判断是否开放了端口。我们知道端口属于网络的应用层,因此需要用ip和端口来探测,这个时候就可以用connect来探测一下,针对TCP协议,connect函数要进行TCP三次握手,如果connect成功,则说明服务器开放了某个端口,如果connect失败,则说明服务器没有开放某个端口。而connect失败是通过超时来控制的,在规定的时间内,connect会发起多次连接,一直执行到超时,才返回错误。默认情况下,connect是阻塞的,而且默认的超时时间为75s,正常情况下,检测网络的连通性都是毫秒级,如果要判断10万台服务器的,用阻塞的默认的connect去做,效率非常低下。因此采用非阻塞的connect,而且需要自定义超时间(我自定义超时时间为5s)。

2、非阻塞connect

  对于阻塞式套接字,调用connect函数将激发TCP的三次握手过程,而且仅在连接建立成功或者出错时才返回;对于非阻塞式套接字,如果调用connect函数会之间返回-1(表示出错),且错误为EINPROGRESS,表示连接建立,建立启动但是尚未完成;如果返回0,则表示连接已经建立,这通常是在服务器和客户在同一台主机上时发生。

  select是一种IO多路复用机制,它允许进程指示内核等待多个事件的任何一个发生,并且在有一个或者多个事件发生或者经历一段指定的时间后才唤醒它。connect本身并不具有设置超时功能,如果想对套接字的IO操作设置超时,可使用select函数。

  对于select和非阻塞connect,注意两点:[1] 当连接成功建立时,描述符变成可写; [2] 当连接建立遇到错误时,描述符变为即可读,也可写,遇到这种情况,可调用getsockopt函数。

3、实现步骤

(1) 创建socket,并利用fcntl将其设置为非阻塞

(2) 调用connect函数,如果返回0,则连接建立;如果返回-1,检查errno ,如果值为 EINPROGRESS,则连接正在建立。

(3) 为了控制连接建立时间,将该socket描述符加入到select的可读可写集合中,采用select函数设定超时。

(4) 如果规定时间内成功建立,则描述符变为可写;否则,采用getsockopt函数捕获错误信息

(5) 恢复套接字的文件状态并返回。

测试代码如下所示:

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 #include <unistd.h>
  5 #include <sys/types.h>          /* See NOTES */
  6 #include <sys/socket.h>
  7 #include <netinet/in.h>
  8 #include <fcntl.h>
  9 #include <errno.h>
 10
 11 int main(int argc, char **argv)
 12 {
 13     if (argc < 3) {
 14         printf("please input ip and port, for example ./main 120.12.34.56 80.\n");
 15         return -1;
 16     }
 17
 18
 19     char *ipaddr = argv[1];
 20     unsigned int port = atoi(argv[2]);
 21
 22     int fd = 0;
 23     struct sockaddr_in  addr;
 24     fd_set fdr, fdw;
 25     struct timeval timeout;
 26     int err = 0;
 27     int errlen = sizeof(err);
 28
 29     fd = socket(AF_INET,SOCK_STREAM,0);
 30     if (fd < 0) {
 31         fprintf(stderr, "create socket failed,error:%s.\n", strerror(errno));
 32         return -1;
 33     }
 34
 35     bzero(&addr, sizeof(addr));
 36     addr.sin_family = AF_INET;
 37     addr.sin_port = htons(port);
 38     inet_pton(AF_INET, ipaddr, &addr.sin_addr);
 39
 40     /*设置套接字为非阻塞*/
 41     int flags = fcntl(fd, F_GETFL, 0);
 42     if (flags < 0) {
 43         fprintf(stderr, "Get flags error:%s\n", strerror(errno));
 44         close(fd);
 45         return -1;
 46     }
 47     flags |= O_NONBLOCK;
 48     if (fcntl(fd, F_SETFL, flags) < 0) {
 49         fprintf(stderr, "Set flags error:%s\n", strerror(errno));
 50         close(fd);
 51         return -1;
 52     }
 53
 54     /*阻塞情况下linux系统默认超时时间为75s*/
 55     int rc = connect(fd, (struct sockaddr*)&addr, sizeof(addr));
 56     if (rc != 0) {
 57         if (errno == EINPROGRESS) {
 58             printf("Doing connection.\n");
 59             /*正在处理连接*/
 60             FD_ZERO(&fdr);
 61             FD_ZERO(&fdw);
 62             FD_SET(fd, &fdr);
 63             FD_SET(fd, &fdw);
 64             timeout.tv_sec = 10;
 65             timeout.tv_usec = 0;
 66             rc = select(fd + 1, &fdr, &fdw, NULL, &timeout);
 67             printf("rc is: %d\n", rc);
 68             /*select调用失败*/
 69             if (rc < 0) {
 70                 fprintf(stderr, "connect error:%s\n", strerror(errno));
 71                 close(fd);
 72                 return -1;
 73             }
 74
 75             /*连接超时*/
 76             if (rc == 0) {
 77                 fprintf(stderr, "Connect timeout.\n");
 78                 close(fd);
 79                 return -1;
 80             }
 81             /*[1] 当连接成功建立时,描述符变成可写,rc=1*/
 82             if (rc == 1 && FD_ISSET(fd, &fdw)) {
 83                 printf("Connect success\n");
 84                 close(fd);
 85                 return 0;
 86             }
 87             /*[2] 当连接建立遇到错误时,描述符变为即可读,也可写,rc=2 遇到这种情况,可调用getsockopt函数*/
 88             if (rc == 2) {
 89                 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
 90                     fprintf(stderr, "getsockopt(SO_ERROR): %s", strerror(errno));
 91                     close(fd);
 92                     return -1;
 93
 94                 }
 95
 96                 if (err) {
 97                     errno = err;
 98                     fprintf(stderr, "connect error:%s\n", strerror(errno));
 99                     close(fd);
100                     return -1;
101
102                 }
103             }
104
105         }
106         fprintf(stderr, "connect failed, error:%s.\n", strerror(errno));
107         return -1;
108     }
109     return 0;
110 }

4、参考资料

http://dongxicheng.org/network/non-block-connect-implemention/

http://www.cnblogs.com/flyxiang2010/archive/2010/12/17/1909051.html

时间: 2024-08-04 03:40:22

Linux下connect超时处理【总结】的相关文章

Linux下connect超时处理

1.前言 最近在写一个测试工具,要求快速的高效率的扫描出各个服务器开放了哪些端口.当时想了一下,ping只能检测ip,判断服务器的网络是连通的,而不能判断是否开放了端口.我们知道端口属于网络的传输层,因此需要用ip和端口来探测,这个时候就可以用connect来探测一下,针对TCP协议,connect函数要进行TCP三次握手,如果connect成功,则说明服务器开放了某个端口,如果connect失败,则说明服务器没有开放某个端口.而connect失败是通过超时来控制的,在规定的时间内,connec

linux下ssh超时时间配置

摘自:https://www.cnblogs.com/flishroom/p/11661515.html Linux下设置超时时间,是在配置文件/etc/profile里.在该文件下,添加一个变量: export TMOUT=60 时间单位是S,上面配置的超时时间是60秒. 60秒无人操作ssh终端,则ssh自动退出. 原文地址:https://www.cnblogs.com/LiuYanYGZ/p/12411251.html

[转] - linux下使用write\send发送数据报 EAGAIN : Resource temporarily unavailable 错

linux下使用write\send发送数据报 EAGAIN : Resource temporarily unavailable 错 首先是我把套接字设置为异步的了,然后在使用write发送数据时采取的方式是循环发送大量的数据:由于是异步的,write\send将要发送的 数据提交到发送缓冲区后是立即返回的,并不需要对端确认数据已接收.在这种情况下是很有可能出现发送缓冲区被填满,导致write\send无法再向缓冲 区提交要发送的数据.因此就产生了Resource temporarily un

Windows 和 Linux下使用socket下载网页页面内容(可设置接收/发送超时)的代码

主要难点在于设置recv()与send()的超时时间,具体要注意的事项,请看代码注释部分,下面是代码: [cpp] view plaincopyprint? #include <stdio.h> #include <sys/types.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <string.h> #ifdef _WIN32   ///

linux下socket connect阻塞方式 阻塞时间控制

同事今天问我,如何在linux下的c代码里面控制connect的阻塞时间.应用的背景是:linux下的c程序有两个目标IP需要connect,如果用阻塞方式,当其中一个IP不能连接的情况下,程序将阻塞在connect函数上.本来以为用setsockopt修改个什么参数就可以搞定,结果baidu了半天也没有结果.倒是在网上搜到很多这样的解决方案:将connect方式设置为非阻塞方式,这样程序一旦执行就会马上返回,但问题是,到底有没有连接上呢,你需要等待一段时间,然后使用函数判断连接是否正常.试了下

linux下telnet mysql的3306断口,提示Can&#39;t connect to MySQL server on localhost (110)

新购买的阿里云ECS服务器,食用lnmp环境,安装完毕后,telnet localhost 3306提示Can't connect to MySQL server on localhost (110): 首先通过命令行查看mysql是否启动 如果mysql已经正常启动,查看端口3306是否分配给msyql 通过查看服务器上3306是正常分配给msyql的 问题就应该出现在防火墙上了,通过 vi /etc/sysconfig/iptables 加入一行 -A RH-Firewall-1-INPUT

关于.Net Core 部署在Linux下连接SqlServer数据库超时解决办法

.Net Core 在 Linux 下连接 SqlServer 需要 SqlServer2008 SP3或以上版本,或SqlServer2012,或SqlServer2014. 如果SqlServer2008低于SP3版本,会出现连接超时的问题. 解决办法: 官方下载SqlServer 2008 Sp3 补丁 https://download.microsoft.com/download/9/6/4/964BB4EC-FC28-4DA7-9295-7D4A8FDBE1A4/CHS/SQLServ

Linux 下centos7启动 Tomcat 抛出Can&#39;t connect to X11 window server 问题的解决方法

1 问题 今天启动 Tomcat 后,登录页验证码不见了.在 localhost.xxx.log 发现以下错误: org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [StickyCaptcha] in context with path [/web2] threw exception [Servlet execution threw an exception] with root

linux下ppp拨号无线上网

linux下用ppp上网需要两个程序:pppd和chat.ubuntu自带pppd和chat,可以使用man查看具体使用方法. 典型的ppp拨号需要准备几个文件: 1. pppd脚本. 2. chat脚本. 3. chap-secrets文件. 4. pap-secrets文件. chat脚本是真正AT指令的发送和接收脚本,chat脚本主要有TIMEOUT,ABORT和AT指令交互等构成.TIMEOUT超时,ABORT指定AT指令交互时,出现什么样的错误chat将退出.AT指令交互是“接收”“发