帮我写一段C语言代码从一个主的udp服务中接收数据并打印
时间: 2023-06-03 19:07:44 浏览: 141
c语言udp服务器端代码
好的,以下是C语言代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s <port>\n", argv[0]);
exit(1);
}
int port = atoi(argv[1]);
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket failed");
exit(1);
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("bind failed");
exit(1);
}
char buf[BUF_SIZE];
while (1) {
ssize_t n = recv(sockfd, buf, BUF_SIZE - 1, 0);
if (n < 0) {
perror("recv failed");
exit(1);
}
buf[n] = '\0';
printf("Received message: %s\n", buf);
}
close(sockfd);
return 0;
}
```
这段代码创建了一个UDP套接字,绑定在指定端口上,并循环接收来自客户端的数据,打印输出。
阅读全文