以下是一个简单的UDP回显服务器和客户端的示例代码。服务器监听在端口9999上,并将接收到的任何消息发送回客户端。客户端连接到服务器并发送消息,然后接收回显。
服务器端 (server.c):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#define BUF_SIZE 1024
#define PORT 9999
int main() {
int server_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (server_fd < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
struct sockaddr_in server_addr;
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);
int bind_ret = bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (bind_ret < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
char buffer[BUF_SIZE];
int read_len;
while (1) {
memset(buffer, 0, BUF_SIZE);
read_len = recvfrom(server_fd, buffer, BUF_SIZE, 0, (struct sockaddr *)&client_addr, &client_addr_len);
if (read_len < 0) {
perror("recvfrom failed");
exit(EXIT_FAILURE);
}
printf("Received message: %s\n", buffer);
int send_ret = sendto(server_fd, buffer, read_len, 0, (struct sockaddr *)&client_addr, client_addr_len);
if (send_ret < 0) {
perror("sendto failed");
exit(EXIT_FAILURE);
}
}
close(server_fd);
return 0;
}
客户端 (client.c):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#define BUF_SIZE 1024
#define PORT 9999
#define SERVER_IP "127.0.0.1"
int main() {
int client_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (client_fd < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr);
char buffer[BUF_SIZE];
printf("Enter message: ");
fgets(buffer, BUF_SIZE, stdin);
int send_ret = sendto(client_fd, buffer, strlen(buffer),