生成基于C语言的udp通信代码
时间: 2023-09-02 22:08:58 浏览: 74
好的,让我来为您生成基于C语言的UDP通信代码。以下是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#define BUF_SIZE 1024
#define PORT 8888
int main() {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
char buffer[BUF_SIZE];
// 创建socket
server_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (server_fd == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
// 设置socket地址
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
// 绑定socket到地址
if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
// 接收客户端数据
socklen_t client_addr_len = sizeof(client_addr);
int data_len = recvfrom(server_fd, buffer, BUF_SIZE, 0, (struct sockaddr*)&client_addr, &client_addr_len);
if (data_len == -1) {
perror("recvfrom");
exit(EXIT_FAILURE);
}
printf("Received data: %s\n", buffer);
// 发送数据给客户端
char* msg = "Hello, client!";
int msg_len = strlen(msg);
int bytes_sent = sendto(server_fd, msg, msg_len, 0, (struct sockaddr*)&client_addr, client_addr_len);
if (bytes_sent == -1) {
perror("sendto");
exit(EXIT_FAILURE);
}
printf("Sent data to client.\n");
close(server_fd);
return 0;
}
```
该代码创建了一个UDP服务器,监听8888端口,并接收客户端发送的数据,并回复一条消息。您可以将代码复制,并粘贴到您的C文件中,并根据您的实际需求进行修改。
阅读全文