怎么设置tcp_keepalive设置
时间: 2023-07-16 21:15:41 浏览: 122
linux tcp keepalive存活代码设置
在Linux系统中,可以使用`setsockopt`函数来设置TCP Keepalive参数。具体步骤如下:
1. 创建一个socket连接
```
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
```
2. 设置keepalive参数
```
int keepAlive = 1; // 开启keepalive
int keepIdle = 60; // 如该连接在60秒内没有任何数据往来,则进行探测
int keepInterval = 5; // 探测时发包的时间间隔为5 秒
int keepCount = 3; // 探测尝试的次数.如果第1次探测包就收到响应了,则后2次的不再发送
setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepAlive, sizeof(keepAlive));
setsockopt(sockfd, SOL_TCP, TCP_KEEPIDLE, (void*)&keepIdle, sizeof(keepIdle));
setsockopt(sockfd, SOL_TCP, TCP_KEEPINTVL, (void *)&keepInterval, sizeof(keepInterval));
setsockopt(sockfd, SOL_TCP, TCP_KEEPCNT, (void *)&keepCount, sizeof(keepCount));
```
3. 连接服务器
```
struct sockaddr_in servaddr;
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
inet_pton(AF_INET, ip, &servaddr.sin_addr);
connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
```
4. 发送和接收数据
```
char sendbuf[1024];
char recvbuf[1024];
while (fgets(sendbuf, sizeof(sendbuf), stdin) != NULL) {
write(sockfd, sendbuf, strlen(sendbuf));
int n = read(sockfd, recvbuf, sizeof(recvbuf));
if (n < 0) {
printf("read error\n");
break;
}
recvbuf[n] = 0;
fputs(recvbuf, stdout);
}
```
5. 关闭socket连接
```
close(sockfd);
```
阅读全文