下面分别是服务器端和客户端的源码, 基于UDP的简单通信
/**
* @name server.c
* @author IYATT-yx
* @brief 套接字UDP通信 - 服务器端
*/
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
int main(void)
{
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1)
{
perror("socket error");
exit(EXIT_FAILURE);
}
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(11111);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(fd, (struct sockaddr *)&server, sizeof(server)) == -1)
{
perror("bind error");
exit(EXIT_FAILURE);
}
struct sockaddr_in client;
socklen_t clientLen = sizeof(client);
char buf[1024] = {0};
// 通信
while (true)
{
// 接收
if (recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *)&client, &clientLen) == -1)
{
perror("recvfrom error");
exit(EXIT_FAILURE);
}
char ipbuf[64];
printf("收到来自%s:%d的数据: %s\n", inet_ntop(AF_INET, &client.sin_addr.s_addr,
ipbuf, sizeof(ipbuf)), ntohs(client.sin_port), buf);
// 回复
memset(buf, 0, sizeof(buf));
strcpy(buf, "服务器已收到数据");
if (sendto(fd, buf, strlen(buf) + 1, 0, (struct sockaddr *)&client, sizeof(client)) == -1)
{
perror("sendto error");
exit(EXIT_FAILURE);
}
}
close(fd);
}
/**
* @name client.c
* @author IYATT-yx
* @brief 套接字UDP通信 - 客户端端
*/
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
int main(void)
{
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1)
{
perror("socket error");
exit(EXIT_FAILURE);
}
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(11111);
inet_pton(AF_INET, "127.0.0.1", &server.sin_addr.s_addr);
while (true)
{
// 发送数据
printf("请输入要发送的内容:");
char buf[1024] = {0};
fgets(buf, sizeof(buf), stdin);
sendto(fd, buf, strlen(buf) + 1, 0, (struct sockaddr *)&server, sizeof(server));
// 接收数据
recvfrom(fd, buf, strlen(buf) + 1, 0, NULL, NULL);
printf("收到服务器的消息: %s\n", buf);
}
close(fd);
}