udpSer.c
#include<myhead.h>
#define SER_IP "192.168.119.143"
#define SER_PORT 7777
int main(int argc, const char *argv[])
{//1.创建int sfd = socket(AF_INET,SOCK_DGRAM,0);if(sfd == -1){perror("socket error");return -1;}//2.连接struct sockaddr_in sin;sin.sin_family = AF_INET;//通讯域sin.sin_port = htons(SER_PORT);//端口号sin.sin_addr.s_addr = inet_addr(SER_IP);//ip地址if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))==-1){perror("bind error");return -1;}printf("bind success\n");//3.数据收发char buf[128]="";struct sockaddr_in cin;//接收对端地址信息socklen_t addrlen = sizeof(cin);//接收地址长度while(1){bzero(buf,sizeof(buf));//清空数据if(recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&cin,&addrlen)==-1)//接收数据{perror("recvfrom error");return -1;}if(strcmp(buf,"quit")==0){printf("服务端退出\n");break;}printf("接收到的数据是:%s\n",buf);bzero(buf,sizeof(buf));strcat(buf,"*-*");if(sendto(sfd,buf,sizeof(buf),0,(struct sockaddr*)&cin,sizeof(cin))==-1)//发送数据{perror("sendto error");return -1;}}//4.关闭close(sfd);return 0;
}
udpCli.c
#include<myhead.h>
#define SER_IP "192.168.119.143"
#define SER_PORT 7777
#define CLI_IP "192.168.119.143"
#define CLI_PORT 9999
int main(int argc, const char *argv[])
{//1.创建套接字int cfd = socket(AF_INET,SOCK_DGRAM,0);if(cfd == -1){perror("socket error");return -1;}//2.绑定struct sockaddr_in cin;//客户端地址cin.sin_family = AF_INET;//地址族cin.sin_port = htons(CLI_PORT);//端口cin.sin_addr.s_addr = inet_addr(CLI_IP);//IP地址if(bind(cfd,(struct sockaddr*)&cin,sizeof(cin))==-1)//绑定{perror("bind error");return -1;}//3.数据收发char buf[128]="";struct sockaddr_in sin;//服务器地址sin.sin_family = AF_INET;//地址族sin.sin_port = htons(SER_PORT);//端口sin.sin_addr.s_addr = inet_addr(SER_IP);//IP地址while(1){bzero(buf,sizeof(buf));//数据初始化printf("请输入>>>");fgets(buf,sizeof(buf),stdin);buf[strlen(buf)-1]=0;sendto(cfd,buf,sizeof(buf),0,(struct sockaddr*)&sin,sizeof(sin));//发送数据if(strcmp(buf,"quit")==0){printf("客户端退出\n");return -1;}recvfrom(cfd,buf,sizeof(buf),0,NULL,NULL);//接收数据printf("接收到的数据是:%s\n",buf);}//4.关闭close(cfd);return 0;
}
效果展示