用c++写一个udpserver
时间: 2023-05-18 18:04:02 浏览: 223
好的,以下是一个简单的UDP服务器的C代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
#define MAXLINE 1024
int main() {
int sockfd;
char buffer[MAXLINE];
struct sockaddr_in servaddr, cliaddr;
// 创建socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
// 绑定地址和端口
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
printf("UDP server started on port %d\n", PORT);
while (1) {
socklen_t len = sizeof(cliaddr);
int n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL, (struct sockaddr *)&cliaddr, &len);
buffer[n] = '\0';
printf("Received message from %s:%d - %s\n", inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port), buffer);
sendto(sockfd, (const char *)buffer, strlen(buffer), MSG_CONFIRM, (const struct sockaddr *)&cliaddr, len);
}
return 0;
}
```
这个UDP服务器会监听8888端口,接收来自客户端的消息并将其回传。你可以通过修改代码来实现你自己的UDP服务器。
阅读全文