多点通信:
广播:
接收端代码:
#include <myhead.h>
int main(int argc, const char *argv[])
{
//创建套接字
int rfd = socket(AF_INET,SOCK_DGRAM,0);
if(rfd == -1)
{
perror("socket error");
return -1;
}
printf("rfd = %d\n",rfd);
//绑定
//填充结构体
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(8888);
sin.sin_addr.s_addr = inet_addr("192.168.114.255");
//绑定
if(bind(rfd,(struct sockaddr*)&sin,sizeof(sin)) == -1)
{
perror("bind error");
return -1;
}
printf("绑定成功\n");
//接收数据
char buf[128] = "";
//填充发送端结构体
struct sockaddr_in cin;
cin.sin_family = AF_INET;
socklen_t socklen = sizeof(cin);
while(1)
{
//清空内容
bzero(buf,sizeof(buf));
//读取信息
recvfrom(rfd,buf,sizeof(buf),0,(struct sockaddr*)&cin,&socklen);
printf("[%s:%d] : %s\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),buf);
}
//关闭套接字
close(rfd);
return 0;
}
服务器广播:
#include <myhead.h>
int main(int argc, const char *argv[])
{
//设置套接字
int sfd = socket(AF_INET,SOCK_DGRAM,0);
if(sfd == -1)
{
perror("socket error");
return -1;
}
printf("sfd = %d\n",sfd);
//将套接字设置成允许广播
int broadcast = 1;
if(setsockopt(sfd,SOL_SOCKET,SO_BROADCAST,&broadcast,sizeof(broadcast)) == -1)
{
perror("setsockopt error");
return -1;
}
printf("广播设置成功\n");
//向广播地址发送信息
//填充接收端地址信息结构体
struct sockaddr_in cin;
cin.sin_family = AF_INET;
cin.sin_port = htons(8888);
cin.sin_addr.s_addr = inet_addr("192.168.114.255");
//发送数据
char buf[128] = "";
while(1)
{
bzero(buf,sizeof(buf));
printf("请输入>>");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]= '\0';
sendto(sfd,buf,sizeof(buf),0,(struct sockaddr*)&cin,sizeof(cin));
printf("发送成功\n");
}
close(sfd);
return 0;
}