如何用C语言编写一个UDP客户端和服务器,实现双向数据通信的示例代码?
时间: 2024-10-24 17:13:08 浏览: 33
在C语言中,我们可以使用标准库中的socket API来编写UDP(用户数据报协议)客户端和服务器程序,这里提供一个简单的双向通信的示例。注意,这个示例假设你已经对网络编程有基本的理解。
首先,创建一个UDP服务器:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/socket.h>
#define PORT 12345
int main() {
int server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
socklen_t addr_len = sizeof(struct sockaddr_in);
char buffer[1024];
// 创建服务器套接字
server_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (server_socket == -1) {
perror("Failed to create socket");
exit(EXIT_FAILURE);
}
// 设置服务器地址
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
// 绑定到端口
if (bind(server_socket, (struct sockaddr *)&server_addr, addr_len) == -1) {
perror("Failed to bind to port");
close(server_socket);
exit(EXIT_FAILURE);
}
printf("Server started, listening on %d\n", PORT);
while (1) {
// 接收来自客户端的数据
recvfrom(server_socket, buffer, sizeof(buffer), 0, (struct sockaddr *)&client_addr, &addr_len);
// 发送回应给客户端
sendto(server_socket, buffer, strlen(buffer), 0, (struct sockaddr *)&client_addr, addr_len);
printf("Received message from %s: %s\n", inet_ntoa(client_addr.sin_addr), buffer);
}
close(server_socket);
return 0;
}
```
接下来,创建一个UDP客户端:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 12345
int main() {
int client_socket;
struct sockaddr_in server_addr;
char message[] = "Hello, Server!";
size_t msg_len = strlen(message);
// 创建客户端套接字
client_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (client_socket == -1) {
perror("Failed to create socket");
exit(EXIT_FAILURE);
}
// 设置服务器地址
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr);
// 发送消息到服务器
if (sendto(client_socket, message, msg_len, 0, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("Failed to send data");
close(client_socket);
exit(EXIT_FAILURE);
}
printf("Message sent to %s:%d\n", SERVER_IP, SERVER_PORT);
// 接收服务器响应
char received_msg[1024];
socklen_t addr_len = sizeof(server_addr);
ssize_t bytes_received = recvfrom(client_socket, received_msg, sizeof(received_msg), 0, (struct sockaddr *)&server_addr, &addr_len);
if (bytes_received > 0) {
printf("Received message from %s: %s\n", inet_ntoa(server_addr.sin_addr), received_msg);
} else {
perror("Failed to receive response");
}
close(client_socket);
return 0;
}
```
运行这两个程序,服务器会监听指定端口,当客户端连接并发送消息时,服务器接收并返回消息。同样,客户端也尝试连接服务器,发送消息,并接收服务器的回应。
阅读全文