当前位置: 首页 > 图文教程 > 操作系统 > Unix/Linux > Linux下Socket连接超时的一种实现方法

Unix/Linux
LINUX下简单命令
初装ubuntu
Redhat AS 3的LANG的设置
Debian版本小知识
2003服务器,安装了IIS6架设网站问题
前几天最严重的一次错误,导致重装
[vsftpd] 只能上传不能下载
修改了usb_linux的do_mount.c的代码
Fedora Core3上ClamAntiVirus的安装
关于我们的BEIYU
html跳转语句
adobe reader for linux 7
中国黑客精英浮出江湖
Linux必学的系统安全命令
发现很多论坛存在注册ID的BUG
了解Linux的时钟
text
Linux下挂载windows硬盘
致像我一样的Linux初学者
现在开始学习openBSD了

Unix/Linux 中的 Linux下Socket连接超时的一种实现方法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-01   浏览: 173 ::
收藏到网摘: n/a

目前各平台通用的设置套接字(Socket)连接超时的办法是:

  1. 创建套接字,将其设置成非阻塞状态。
  2. 调用connect连接对端主机,如果失败,判断当时的errno是否为EINPROGRESS,也就是说是不是连接正在进行中,如果是,转到步骤3,如果不是,返回错误。
  3. 用select在指定的超时时间内监听套接字的写就绪事件,如果select有监听到,证明连接成功,否则连接失败。
  以下是Linux环境下的示例代码:


#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <time.h>

int main(int argc, char *argv[])
{
        int fd, retval;
        struct sockaddr_in addr;
        struct timeval timeo =