setsockopt和sendto搭配使用例子
时间: 2023-11-22 15:39:48 浏览: 96
socket setsocketopt函数的使用示例
setsockopt函数用于设置套接字选项,sendto函数用于向指定的目标地址发送数据。下面是一个setsockopt和sendto搭配使用的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
int sockfd;
struct sockaddr_in server_addr;
char buffer[1024];
// 创建套接字
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
// 设置套接字选项
int optval = 1;
socklen_t optlen = sizeof(optval);
if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen) < 0) {
perror("setsockopt failed");
exit(EXIT_FAILURE);
}
// 发送数据
const char* message = "Hello, server!";
if (sendto(sockfd, message, strlen(message), 0, (struct sockaddr*) &server_addr, sizeof(server_addr)) < 0) {
perror("sendto failed");
exit(EXIT_FAILURE);
}
printf("Message sent to server.\n");
close(sockfd);
return 0;
}
```
阅读全文