博客
关于我
linux网络编程二十:socket选项:SO_RCVTIMEO和SO_SNDTIMEO
阅读量:805 次
发布时间: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/

你可能感兴趣的文章
MySQL处理千万级数据分页查询的优化方案
查看>>
mysql备份
查看>>
mysql备份与恢复
查看>>
mysql备份工具xtrabackup
查看>>
mysql备份恢复出错_尝试备份/恢复mysql数据库时出错
查看>>
mysql复制内容到一张新表
查看>>
mysql复制表结构和数据
查看>>
mysql复杂查询,优质题目
查看>>
MySQL外键约束
查看>>
MySQL多表关联on和where速度对比实测谁更快
查看>>
MySQL多表左右连接查询
查看>>
mysql大批量删除(修改)The total number of locks exceeds the lock table size 错误的解决办法
查看>>
mysql如何做到存在就更新不存就插入_MySQL 索引及优化实战(二)
查看>>
mysql如何删除数据表,被关联的数据表如何删除呢
查看>>
MySQL如何实现ACID ?
查看>>
mysql如何记录数据库响应时间
查看>>
MySQL子查询
查看>>
Mysql字段、索引操作
查看>>
mysql字段的细节(查询自定义的字段[意义-行列转置];UNION ALL;case-when)
查看>>
mysql字段类型不一致导致的索引失效
查看>>