scoketcan setsockopt用法
时间: 2023-08-17 09:14:43 浏览: 90
下面是一个使用 setsockopt 函数设置 SO_REUSEADDR 选项的例子:
```c++
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
std::cerr << "Failed to create socket." << std::endl;
return 1;
}
// 设置 SO_REUSEADDR 选项,允许在绑定端口时重用该端口
int reuse = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) == -1) {
std::cerr << "Failed to set SO_REUSEADDR option." << std::endl;
close(sockfd);
return 1;
}
sockaddr_in server_address{};
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(8080);
if (bind(sockfd, reinterpret_cast<sockaddr *>(&server_address), sizeof(server_address)) == -1) {
std::cerr << "Failed to bind socket." << std::endl;
close(sockfd);
return 1;
}
if (listen(sockfd, SOMAXCONN) == -1) {
std::cerr << "Failed to listen on socket." << std::endl;
close(sockfd);
return 1;
}
std::cout << "Listening on port 8080..." << std::endl;
while (true) {
int client_sockfd = accept(sockfd, nullptr, nullptr);
if (client_sockfd == -1) {
std::cerr << "Failed to accept client connection." << std::endl;
continue;
}
std::cout << "Accepted client connection." << std::endl;
const char *message = "Hello, client!";
if (send(client_sockfd, message, strlen(message), 0) < 0) {
std::cerr << "Failed to send message to client." << std::endl;
}
close(client_sockfd);
}
close(sockfd);
return 0;
}
```
在上面的例子中,我们先创建了一个套接字,然后使用 setsockopt 函数设置 SO_REUSEADDR 选项,允许在绑定端口时重用该端口。接下来绑定端口、监听连接请求,并在循环中接受客户端连接并向客户端发送数据。
阅读全文