UDP的特点: 无连接 不可靠的 数据报服务
无连接:两个主机可以直接发送数据,不需要建立连接
不可靠:UDP不保证数据能够到达对端,不保证数据的完整性,正确性,乱序 重复
数据报服务:数据是一段一段的。发送方sendto的次数和接收方接收数据的次数是相等的。sendto-次发送的数据由接收方一次recvfrom获取如果一次recvtrom没有将UDP报文段中的数据读取完成,则剩下的数据会被丢弃
UDP编程流程:
服务器:socket bind recvfrom sendto close
客户端:socket bind sendto recvfrom close
int recvfrom(int sockfd, void *buff, size_t len, int flag,struct sockaddr*src_addr, socklen_t *len);
int sendto(int sockfd,void *buff size_t len, int flag,struct sockaddr * dest_addr, socklen_t len);
struct sockaddr* dest_addr指定数据发送给那个主机上的那个进程
server
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main()
{
int sockfd=socket(AF_INET,SOCK_DGRAM,0);
assert(-1!=sockfd);
struct sockaddr_in ser;
memset(&ser,0,sizeof(ser));//清空
ser.sin_family=AF_INET;//IPv4地址族
ser.sin_port=htons(6500);//主机到网络的short型,给服务器指定端口号
ser.sin_addr.s_addr=inet_addr("127,0,0,2");
int res=bind(sockfd,(struct sockaddr*)&ser,sizeof(ser));
while(1)
{
char buff[128]={0};
struct sockaddr_in cli;
int len=sizeof(cli);
int n=recvfrom(sockfd,buff,10,0,(struct sockaddr*)&cli,&len);
if(n<=0)
{
printf("error\n");
continue;
}
printf("ip:%s, port: %d\n",inet_ntoa(cli.sin_addr),ntohs(cli.sin_port));
printf("n==%d: %s\n",n,buff);
sendto(sockfd,"OK",2,0,(struct sockaddr*)&cli,sizeof(cli));
}
}
client
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <netinet/in.h>//字节序列转换函数所用
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>//地址转换函数所用
int main()
{
int sockfd=socket(AF_INET,SOCK_DGRAM,0);
assert(-1!=sockfd);
struct sockaddr_in ser;
memset(&ser,0,sizeof(ser));
ser.sin_family=AF_INET;
ser.sin_port=htons(6500);
ser.sin_addr.s_addr=inet_addr("127.0.0.2");
while(1)
{
printf("please input: ");
char data[128]={0};
fgets(data,128,stdin);
if(strncmp(data,"bye",3)==0)
{
close(sockfd);
break;
}
sendto(sockfd,data,strlen(data)-1,0,(struct sockaddr*)&ser,sizeof(ser));
char buff[128]={0};
int n=recvfrom(sockfd,buff,127,0,NULL,NULL);
if(n<=0)
{
printf("error\n");
break;
}
printf("n==%d: %s\n",n,buff);
}
}