(一)实现流程
(二)代码实现
(1)服务器端
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
void udp_ser()
{
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
{
perror("socket err");
return;
}
struct sockaddr_in saddr, caddr;
memset(&saddr, 0, sizeof(saddr));
memset(&caddr, 0, sizeof(caddr));
int len_saddr = sizeof(saddr);
int len_caddr = sizeof(caddr);
saddr.sin_family = AF_INET;
saddr.sin_port = htons(8000);
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
int ret = bind(sockfd, (struct sockaddr*)&saddr, len_saddr);
if(ret == -1)
{
perror("bind err");
return;
}
while (1)
{
char buff[128] = {0};
ret = recvfrom(sockfd, buff, 127, 0, (struct sockaddr *)&caddr, &len_caddr);
if (ret == -1)
{
printf("ip = %s, port = %d已退出\n", inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port));
break;
}
printf("ip = %s, port = %d, msg:%s\n", inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port), buff);
sendto(sockfd, "ok", 2, 0, (struct sockaddr *)&caddr, len_caddr);
}
close(sockfd);
}
int main()
{
udp_ser();
return 0;
}
(2)客户端
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
void udp_cli()
{
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd == -1)
{
perror("socket err");
return;
}
struct sockaddr_in saddr, caddr;
memset(&saddr, 0, sizeof(saddr));
memset(&caddr, 0, sizeof(caddr));
int len_saddr = sizeof(saddr);
int len_caddr = sizeof(caddr);
saddr.sin_family = AF_INET;
saddr.sin_port = htons(8000);
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
while(1)
{
printf("input: ");
fflush(stdout);
char buff[128] = {0};
fgets(buff, 127, stdin);
if(strncmp(buff, "end", 3) == 0)
{
break;
}
sendto(sockfd, buff, strlen(buff), 0, (struct sockaddr*)&saddr, len_saddr);
memset(buff, 0, 128);
int ret = recvfrom(sockfd, buff, 127, 0, (struct sockaddr*)&caddr, &len_caddr);
if(ret <= 0)
{
perror("ser exit");
break;
}
printf("ser: %s\n", buff);
}
close(sockfd);
}
int main()
{
udp_cli();
return 0;
}
(3)测试结果
|