一.UDP通信流程
1.server:
1.创建一个socket()
2.bind()
3.recvfrom()
4.sendto()
5.close()
2.client:
1.socket
2.sendto()
3.recvfrom()
4.close()
二.涉及到的api
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen);
-参数:
sockfd : 通信的fd
buf : 要发送的数据
len : 发送数据的长度
flags : 0
dest_addr : 通信的另外一端的地址信息
addrlen : 地址的内存大小
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen);
-参数:
-sockfd:通信的fd
-buf:接收数据的数组
-len:数组的大小
-flags:0
-src_addr : 用来保存另外一段的地址信息,不需要指定为NULL
-socklen_t:地址的内存大小
三.udp服务端和客户端代码实现
1.服务端
#include <stdio.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int udp_sockfd = socket(AF_INET,SOCK_DGRAM,0);
if(udp_sockfd == -1)
{
perror("socket");
exit(-1);
}
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(8000);
int opt = 1;
setsockopt(udp_sockfd,SOL_SOCKET,SO_REUSEPORT,(const void*)&opt,sizeof(opt));
if(bind(udp_sockfd,(const struct sockaddr*)&server,sizeof(server)) == -1)
{
perror("bind");
exit(-1);
}
char recvbuff[1024];
struct sockaddr_in clienaddr;
int len = sizeof(clienaddr);
char client_ip[16] = {0};
unsigned int client_port = 0;
while(1)
{
memset(recvbuff,0,sizeof(recvbuff));
//接收数据
int num = recvfrom(udp_sockfd,recvbuff,sizeof(recvbuff),0,
(struct sockaddr*)&clienaddr,&len);
if(num == -1)
{
perror("recvfrom");
exit(-1);
}
printf("recv data:%s,client ip : %s, client port : %d\n",recvbuff,
inet_ntop(AF_INET,(const void*)&clienaddr.sin_addr.s_addr,client_ip,sizeof(client_ip)),
ntohs(clienaddr.sin_port));
//发送数据
sendto(udp_sockfd,recvbuff,strlen(recvbuff)+1,0,
(const struct sockaddr*)&clienaddr,sizeof(clienaddr));
}
close(udp_sockfd);
return 0;
}
2.客户端
#include <stdio.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int udp_sockfd = socket(AF_INET,SOCK_DGRAM,0);
if(udp_sockfd == -1)
{
perror("socket");
exit(-1);
}
char recvbuff[1024];
char *sendbuf;
//服务器地址信息
struct sockaddr_in saddr;
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
saddr.sin_port = htons(8000);
int len = sizeof(saddr);
while(1)
{
printf("亲爱的用户,请您输入你想要发送给服务器的信息:");
scanf("%s",sendbuf);
//发送数据
sendto(udp_sockfd,sendbuf,strlen(sendbuf)+1,0,
(const struct sockaddr*)&saddr,sizeof(saddr));
memset(recvbuff,0,sizeof(recvbuff));
//接收数据
int num = recvfrom(udp_sockfd,recvbuff,sizeof(recvbuff),0,
NULL,NULL);
if(num == -1)
{
perror("recvfrom");
exit(-1);
}
printf("接收到回射信息:%s\n",recvbuff);
}
close(udp_sockfd);
return 0;
}