//UDP服务器的搭建
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define ERR_MSG(msg) do{\
fprintf(stderr,"line:%d\n",__LINE__);\
perror(msg);\
}while(0)
int main(int argc, const char *argv[])
{
//创建报式套接字
int sfd=socket(AF_INET,SOCK_DGRAM,0);
if(sfd<0)
{
ERR_MSG("socket");
return -1;
}
//填充服务器的IP和端口
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(8888);//服务器绑定的端口号,1024~49151
sin.sin_addr.s_addr=inet_addr("192.168.52.177");//服务器绑定的IP,ifconfig查看
//绑定服务器自身的IP和端口--->必须绑定
if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))<0)
{
ERR_MSG("bind");
return -1;
}
printf("bind success\n");
//存储数据包从哪里发过来
struct sockaddr_in cin;
socklen_t addrlen=sizeof(cin);
char buf[128]="";
ssize_t ret=0;
while(1)
{
bzero(buf,sizeof(buf));
//接收数据
ret=recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&cin,&addrlen);
if(ret<0)
{
ERR_MSG("recvfrom");
return -1;
}
printf("[%s:%d] buf=%s\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),buf);
//发送数据
strcat(buf,"123");
if(sendto(sfd,buf,sizeof(buf),0,(struct sockaddr*)&cin,addrlen)<0)
{
ERR_MSG("sendto");
return -1;
}
printf("send success\n");
}
//关闭文件描述符
close(sfd);
return 0;
}
//UDP客户端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define ERR_MSG(msg) do{\
fprintf(stderr,"line:%d\n",__LINE__);\
perror(msg);\
}while(0)
int main(int argc, const char *argv[])
{
//创建报式套接字
int sfd=socket(AF_INET,SOCK_DGRAM,0);
if(sfd<0)
{
ERR_MSG("socket");
return -1;
}
//填充服务器的IP和端口
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(8888);//服务器绑定的端口号,1024~49151
sin.sin_addr.s_addr=inet_addr("192.168.52.177");//服务器绑定的IP,ifconfig查看
//填充客户端的IP和端口
struct sockaddr_in cin;
cin.sin_family = AF_INET;
cin.sin_port = htons(6666);//客户端绑定的端口号 1024~49151
cin.sin_addr.s_addr = inet_addr("192.168.52.177");//客户端运行后所在环境的IP
//绑定客户端自身的IP和端口--->非必须绑定
if(bind(sfd,(struct sockaddr*)&cin,sizeof(cin))<0)
{
ERR_MSG("bind");
return -1;
}
printf("bind success\n");
//存储数据包从哪里发过来
struct sockaddr_in rcvaddr;
socklen_t addrlen=sizeof(rcvaddr);
char buf[128]="";
ssize_t ret=0;
while(1)
{
bzero(buf,sizeof(buf));
printf("please input:");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
//发送数据给服务器,所以地址信息结构体应该填服务器的地址信息
if(sendto(sfd,buf,sizeof(buf),0,(struct sockaddr*)&sin,sizeof(sin))<0)
{
ERR_MSG("sendto");
return -1;
}
printf("sendto success\n");
//接收数据
ret=recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&rcvaddr,&addrlen);
if(ret<0)
{
ERR_MSG("recvfrom");
return -1;
}
if(ret=0)
{
printf("退出\n");
break;
}
printf("buf=%s\n",buf);
}
//关闭文件描述符
close(sfd);
return 0;
}
运行结果: