代码实现:分为udpSer.c(服务器端)和udpCli.c(客户端)
//udpSer.c
#include <myhead.h>
#define SER_PORT 9999
#define SER_IP "192.168.83.128"
int main(int argc, const char *argv[])
{
//1、创建用于通信的服务器套接字文件描述符
int sfd = socket(AF_INET,SOCK_DGRAM,0);
if(sfd == -1)
{
perror("socket error");
return -1;
}
printf("sfd = %d\n", sfd); //3
//端口号快速重用
int reuse = 1;
if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse)) == -1)
{
perror("setsockopt error");
return -1;
}
printf("端口号快速重用成功\n");
//2、绑定ip地址和端口号
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(SER_PORT);
sin.sin_addr.s_addr = inet_addr(SER_IP);
//2.2绑定工作
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));
//从套接字中读取数据
recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr *)&cin,&addrlen);
printf("收到消息为:%s\n",buf);
strcat(buf,"*+*");
if((sendto(sfd,buf,strlen(buf),0,(struct sockaddr *)&cin,sizeof(cin))) == -1)
{
perror("发送 error");
return -1;
}
}
//4、关闭文件描述符
close(sfd);
return 0;
}
//udpCli.c
#include <myhead.h>
#define SER_PORT 9999
#define SER_IP "192.168.83.128"
#define CLI_PORT 3333
#define CLI_IP "192.168.83.128"
int main(int argc, const char *argv[])
{
//1、创建用于通信的服务器套接字文件描述符
int cfd = socket(AF_INET,SOCK_DGRAM,0);
if(cfd == -1)
{
perror("socket error");
return -1;
}
printf("cfd = %d\n", cfd); //3
//将端口号快速重用
int reuse = 1;
if(setsockopt(cfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))==-1)
{
perror("setsockopt error");
return -1;
}
printf("端口号快速重用成功\n");
//2、绑定ip地址和端口号
struct sockaddr_in cin;
cin.sin_family = AF_INET;
cin.sin_port = htons(CLI_PORT);
cin.sin_addr.s_addr = inet_addr(CLI_IP);
//2.2绑定工作
if(bind(cfd,(struct sockaddr *)&cin,sizeof(cin)) == -1)
{
perror("bind error");
return -1;
}
printf("bind success\n");
//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);
while(1)
{
printf("请输入>>>");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf) - 1] = 0;
//将数据发送给服务器
sendto(cfd,buf,strlen(buf),0,(struct sockaddr*)&sin,sizeof(sin));
printf("发送成功\n");
bzero(buf,sizeof(buf));
recvfrom(cfd,buf,sizeof(buf),0,NULL,NULL);
printf("收到服务器消息为:%s\n",buf);
}
//4、关闭文件描述符
close(cfd);
return 0;
}
输出结果如下:成功从客户端发送信息到服务器中