博客
关于我
linux网络编程二十:socket选项:SO_RCVTIMEO和SO_SNDTIMEO
阅读量:793 次
发布时间:2023-02-05

本文共 1698 字,大约阅读时间需要 5 分钟。

SO_RCVTIMEO和SO_SNDTIMEO是Linux系统中用来设置socket接收和发送数据超时时间的两个选项。它们分别用于限制与数据传输相关的系统调用,如send、recv、accept和connect等操作的等待时间。

当超时发生时,这些系统调用会返回-1,并设置 errno为EAGAIN或EWOULDBLOCK。需要注意的是,connect操作的超时错误会返回EINPROGRESS,这与其他操作不同。

以下是如何设置socket连接超时的实现代码:

#include 
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
int timeout_connect(const char *ip, int port, int time) { int ret = 0; int error; struct sockaddr_in address; bzero(&address, sizeof(address)); address.sin_family = AF_INET; address.sin_port = htons(port); inet_pton(AF_INET, ip, &address.sin_addr); int sockfd = socket(PF_INET, SOCK_STREAM, 0); if (sockfd == -1) { return -1; } struct timeval timeout; timeout.tv_sec = time; timeout.tv_usec = 0; socklen_t len = sizeof(timeout); ret = setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, len); if (ret == -1) { error = errno; while ((close(sockfd) == -1) && (errno == EINTR)) { ; } errno = error; return -1; } ret = connect(sockfd, (struct sockaddr *)&address, sizeof(address)); if (ret == -1) { if (errno == EINPROGRESS) { printf("连接超时\n"); return -1; } printf("发生连接错误\n"); return -1; } char buffer[1024]; memset(buffer, '\0', 1024); ret = recv(sockfd, buffer, 1024, 0); printf("接收到的字节数:%d,内容:%s\n", ret, buffer); return sockfd;}

主函数部分:

int main(int argc, char **argv) {    if (argc != 3) {        fprintf(stderr, "Usage: %s ip port\n", argv[0]);        return 1;    }    const char *ip = argv[1];    int port = atoi(argv[2]);    int sockfd = timeout_connect(ip, port, 10);    if (sockfd < 0) {        return 1;    }    return 0;}

以上代码示例展示了如何在socket连接中设置发送数据的超时时间,并在超时时处理错误情况。

转载地址:http://jmkfk.baihongyu.com/

你可能感兴趣的文章
Linux系统调优实战
查看>>
Linux系统调用分析
查看>>
Linux系统轻量应用服务器CPU使用率高的排查与解决方案
查看>>
Linux系统通过netstat查看网络状态、端口状态
查看>>
Linux系统配置静态IP地址步骤
查看>>
linux系统重命名文件名,但文件名有空格如何处理
查看>>
linux线程
查看>>
linux线程同步的含义,Linux线程同步——条件变量
查看>>
Linux线程编程之生产者消费者问题
查看>>
linux终端 知乎,为 Linux 爱好者打造的极简 Mac 终端 | Linux 中国
查看>>
Linux终端调试大全(非常详细)零基础入门到精通,收藏这一篇就够了
查看>>
Linux经典系统故障汇总与排障技巧及排障汇总表
查看>>
Linux经常使用命令(一) - ls
查看>>
Linux经常使用命令(十一) - more
查看>>
Linux经常使用命令(十二) - less
查看>>
linux经常使用(一)linux 安装配置 jdk之 找不到安装文件文件夹及source /etc/profile 报unexpected end of file 错误 解决...
查看>>
Linux给/根目录直接扩容_Linux直接给系统盘扩容_Mysql数据盘满了_不用外挂数据盘_迁移mysql数据_直接扩容---Linux工作笔记073
查看>>
linux给用户改变组,Linux用户及用户组的建立,修改和删除
查看>>
linux给用户添加sudo权限
查看>>
linux缓存nscd
查看>>