一、UDP通信流程
二、代码实现
1.服务器
代码如下(示例):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
int main()
{
// 1.创建一个通信的socket
int fd = socket(PF_INET, SOCK_DGRAM, 0);
if (fd == -1)
{
perror("socket");
exit(-1);
}
// 2.绑定
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(9999);
addr.sin_addr.s_addr = INADDR_ANY;
int ret = bind(fd, (struct sockaddr*)&addr, sizeof(addr));
if (ret == -1)
{
perror("bind");
exit(-1);
}
// 3.通信
while (1)
{
char buf[128];
char ipbuf[16];
struct sockaddr_in caddr;
int len = sizeof(caddr);
//接受数据
int num = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *)&caddr, &len);
printf("client ip:%s,port :%d\n",
inet_ntop(AF_INET, &caddr.sin_addr.s_addr, ipbuf, sizeof(ipbuf)),
ntohs(caddr.sin_port));
printf("client say:%s\n", buf);
//发送数据
sendto(fd, buf, strlen(buf) + 1,0,(struct sockaddr*)&caddr,sizeof(caddr));
}
close(fd);
return 0;
}
2.客户端
代码如下(示例):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
int main()
{
// 1.创建一个通信的socket
int fd = socket(PF_INET, SOCK_DGRAM, 0);
if (fd == -1)
{
perror("socket");
exit(-1);
}
//服务器地址信息
struct sockaddr_in saddr;
saddr.sin_family = AF_INET;
saddr.sin_port = htons(9999);
inet_pton(AF_INET, "182.61.11.197", &saddr.sin_addr.s_addr);
int num = 0;
// 3.通信
while (1)
{
char buf[128];
sprintf(buf, "hello ,i am client %d\n", num++);
//发送数据
sendto(fd, buf, strlen(buf) + 1,0,(struct sockaddr*)&saddr,sizeof(saddr));
//接受数据
int num = recvfrom(fd, buf, sizeof(buf), 0, NULL, NULL);
printf("server say:%s\n", buf);
sleep(1);
}
close(fd);
return 0;
}