用setsockopt()函数实现允许地址快速重用,以及设置接收10秒超时的相关服务器和客户端代码
时间: 2024-02-18 15:59:21 浏览: 126
setsockopt()设置socket方法
以下是使用setsockopt()函数实现允许地址快速重用和设置接收10秒超时的相关服务器和客户端代码:
服务器端代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[]) {
int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
// 允许地址重用
int optval = 1;
if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
// 设置10秒超时
struct timeval timeout = {10, 0};
if (setsockopt(listen_fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) == -1) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(listen_fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
if (listen(listen_fd, 10) == -1) {
perror("listen");
exit(EXIT_FAILURE);
}
while (1) {
int conn_fd = accept(listen_fd, NULL, NULL);
if (conn_fd == -1) {
if (errno == EINTR) {
continue;
}
perror("accept");
exit(EXIT_FAILURE);
}
// 处理连接
close(conn_fd);
}
close(listen_fd);
return 0;
}
```
客户端代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[]) {
int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (sock_fd == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
// 设置10秒超时
struct timeval timeout = {10, 0};
if (setsockopt(sock_fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) == -1) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(sock_fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("connect");
exit(EXIT_FAILURE);
}
// 发送数据
const char *msg = "hello";
if (send(sock_fd, msg, strlen(msg), 0) == -1) {
perror("send");
exit(EXIT_FAILURE);
}
char buf[1024];
int len = recv(sock_fd, buf, sizeof(buf), 0);
if (len == -1) {
if (errno == EINTR) {
printf("timeout\n");
} else {
perror("recv");
exit(EXIT_FAILURE);
}
} else {
buf[len] = '\0';
printf("recv: %s\n", buf);
}
close(sock_fd);
return 0;
}
```
阅读全文