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;
}
效果展示