UDP单向通信

服务端
server.c

#include
#include//exit 
#include//socket
#include//sockaddr_in
#include//htons inet_addr
#include
#include
int main(int argc, char const *argv[])
{
	if(argc < 3)
	{
		fprintf(stderr,"%s ip port\n",argv[0]);
		exit(1);
	}
	//创建通信套接字 
	int fd = socket(AF_INET,SOCK_DGRAM,0);
	if(fd == -1)
	{
		perror("socket()");
		exit(1);
	}
	printf("fd = %d\n",fd);
	
	//绑定套接字IP地址和端口
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr(argv[1]);
	addr.sin_port = htons(atoi(argv[2])) ;
	
	bind(fd,(struct sockaddr *)&addr,sizeof(addr));
	
	char buff[128] = {};
	//通信
	struct sockaddr_in caddr;
	int caddrlen = sizeof(caddr);
	//接收数据
     while(1)
       {
	if(recvfrom(fd,buff,sizeof(buff),0,(struct sockaddr *)&caddr,&caddrlen)==-1)
	{
		perror("fail to recvfrom");
		exit(1);
	 }
	 printf("ip:%s , port:%d\n",inet_ntoa(caddr.sin_addr),ntohs(caddr.sin_port));
	 printf("client : %s\n",buff);
	 if(sendto(fd,buff,sizeof(buff),0,(struct sockaddr *)&caddr,sizeof(caddr)) == -1)
	 {
	 	perror("fail to sendto");
	 	exit(1);
	 }
        }
	 
	 //删除套接字
	 close(fd);
}
	

客服端
client.c

#include
#include//exit 
#include//socket
#include//sockaddr_in
#include//htons inet_addr
#include
#include
int main(int argc, char const *argv[])
{
	if(argc < 3)
	{
		fprintf(stderr,"%s ip port\n",argv[0]);
		exit(1);
	}
	//创建通信套接字 
	int fd = socket(AF_INET,SOCK_DGRAM,0);
	if(fd == -1)
	{
		perror("socket()");
		exit(1);
	}
	printf("fd = %d\n",fd);
	
	//绑定套接字IP地址和端口
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr(argv[1]);
	addr.sin_port = htons(atoi(argv[2])) ;
	
//	bind(fd,(struct sockaddr *)&addr,sizeof(addr));
	
	char buff[128] = {};
	//通信
	struct sockaddr_in caddr;
	int caddrlen = sizeof(caddr);
	while(1)
	{
	fgets(buff,sizeof(buff),stdin);
	buff[strlen(buff)-1]='\0';
        if(sendto(fd,buff,sizeof(buff),0,(struct sockaddr *)&addr,sizeof(addr)) == -1)
	 {
	 	perror("fail to sendto");
	 	exit(1);
	 }
	//接收数据
	if(recvfrom(fd,buff,sizeof(buff),0,(struct sockaddr *)&caddr,(socklen_t *)&caddrlen)==-1)
	{
		perror("fail to recvfrom");
		exit(1);
	 }
	 printf("ip:%s , port:%d\n",inet_ntoa(caddr.sin_addr),ntohs(caddr.sin_port));
	 printf("client : %s\n",buff);
	/* if(sento(fd,buff,sizeof(buff),0,(struct sockaddr *)&caddr,sizeof(caddr)) == -1)
	 {
	 	perror("fail to sendto");
	 	exit(1);
	 }*/
    } 
	 //删除套接字
	 close(fd);
}
	

运行结果
UDP单向通信_第1张图片
UDP单向通信_第2张图片
UDP单向通信_第3张图片
代码来源https://www.bilibili.com/video/BV17y4y137hx?p=3&spm_id_from=pageDriver

你可能感兴趣的:(网络编程,udp,网络,网络协议)