setsockopt函数服务端怎么使用例子c语言
时间: 2023-12-12 17:01:17 浏览: 68
socket setsocketopt函数的使用示例
下面是一个简单的例子,展示了如何在服务端使用setsockopt函数:
```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>
#define PORT 8080
#define MAX_CLIENTS 10
int main(int argc, char const *argv[]) {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char* hello = "Hello from server";
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// Binding socket to the address and port
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// Listening for incoming connections
if (listen(server_fd, MAX_CLIENTS) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
// Accepting incoming connections
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
// Reading data from the client
valread = read(new_socket, buffer, 1024);
printf("%s\n", buffer);
// Sending data to the client
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sent\n");
return 0;
}
```
在这个例子中,我们使用了setsockopt函数来设置socket的选项。我们设置了SO_REUSEADDR和SO_REUSEPORT选项,这允许我们在同一端口上重新启动服务器,而无需等待几分钟以使先前的套接字关闭。这是一个非常有用的选项,因为在调试和开发时,我们经常需要重新启动服务器。
此外,在这个例子中,我们还使用了bind、listen和accept函数来绑定、监听和接受客户端的连接。我们还使用了read和send函数来读取和发送数据。
阅读全文