setsockopt如何设置连接超时
时间: 2023-11-22 09:50:01 浏览: 176
setsockopt函数可以用来设置套接字选项,包括超时时间。下面是一个示例代码,演示如何使用setsockopt函数设置连接超时时间为5秒:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char *argv[]) {
int sockfd;
struct sockaddr_in servaddr;
char *ip = "127.0.0.1";
int port = 8080;
sockfd = socket(AF_INET, SOCK_STREAM,0);
if (sockfd < 0) {
perror("socket error");
exit(1);
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET; servaddr.sin_port = htons(port);
if (inet_pton(AF_INET, ip, &servaddr.sin_addr) <= 0) {
printf("[%s:%d] is not a valid IPaddress\n", ip, port);
exit(1);
}
struct timeval timeout;
timeout.tv_sec = 5; // 设置超时时间为5秒
timeout.tv_usec = 0;
if (setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) < 0) {
perror("setsockopt error");
exit(1);
}
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
if (errno == EINPROGRESS) {
printf("connecting timeout\n");
exit(1);
}
perror("connect error");
exit(1);
}
printf("connect success\n");
close(sockfd);
return 0;
}
```
阅读全文