[百晓生]-linux广播技术
1)本学期学的ARP协议和NTP协议都属于广播技术的实现,所以借此机会了解下广播技术的底层原理
2)在IP地址中,如果最后一个数字为255,则一定是一个广播地址
3)广播地址分为网络广播地址/受限广播地址/子网广播地址和全部子网广播地址
4)在设计广播程序时,要进行套接字的属性设置
5)广播通信要采用UDP的方式
6)广播套接字的属性为SO_BROADCAST
7)广播地址为INADDR_BROADCAST,同时也要指定发送的端口
2.实例操作
1)实现一个基于C/S模式的广播通信,服务器端程序负责创建广播组,并提供一个键盘输入接口,输入的信息向组内成员广播发送
2)客户端加入广播组,接收服务端的信息并显示,若发现信息中包含quit,则退出程序
3)源代码
服务器端:
//serverbroad.c
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <errno.h>
#define BUFFSIZE
#define PORT 5050
int main()
{
int serversocket;
struct sockaddr_in serveraddress,clientaddress;
int so_broadcast = 1;
socklen_t size;
if((serversocket=(socket(AF_INET,SOCK_DGRAM,0))) < 0)
{
perror("socket");
return 0;
}
if(setsockopt(serversocket,SOL_SOCKET,SO_BROADCAST,&so_broadcast,sizeof(so_broadcast)) < 0)
{
perror("setsockopt");
return 0;
}
serveraddress.sin_family=AF_INET;
serveraddress.sin_port=htons(INADDR_ANY);
serveraddress.sin_addr.s_addr= htonl(INADDR_BROADCAST);
if((bind(serversocket,(struct sockaddr *)&serveraddress, sizeof(struct sockaddr))) < 0)
{
perror("bind");
return 0;
}
clientaddress.sin_family=AF_INET;
clientaddress.sin_port=htons(PORT);
clientaddress.sin_addr.s_addr= htonl(INADDR_BROADCAST);
while (1)
{
char buf[200];
printf("please input your word:>");
scanf("%s",buf);
if((sendto(serversocket,buf,strlen(buf),0,(struct sockaddr *)&clientaddress,sizeof(clientaddress))) < 0)
{
perror("sendto error");
return 0;
}
else
printf("send msg %s\n",buf);
}
return 0;
}
客户端:
//clientbroad.c
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <errno.h>
int main()
{
int clientsocket;
struct sockaddr_in serveraddress,clientaddress;
clientsocket = socket(AF_INET, SOCK_DGRAM, 0);
serveraddress.sin_family = AF_INET;
serveraddress.sin_port = htons(5050);
serveraddress.sin_addr.s_addr = htonl(INADDR_ANY);
int opt = 1;
if(setsockopt(clientsocket, SOL_SOCKET, SO_REUSEADDR,&opt, sizeof(opt)) < 0)
{
perror("setsockopt:SO_REUSEADDR");
return 0;
}
if(bind(clientsocket,(struct sockaddr*)&serveraddress,sizeof(struct sockaddr)) != 0)
{
perror("bind");
return 0;
}
char buf[200];
while (1)
{
memset(buf,0,200);
int size = 0;
size = recvfrom(clientsocket,buf,200,0, (struct sockaddr *)&serveraddress,sizeof(serveraddress));
buf[size] = '\0';
printf("IP:%s msg:%s\n",inet_ntoa(serveraddress.sin_addr),buf);
if(strcmp(buf,"quit") == 0)
{
printf("system quit!!!!\n");
close(clientsocket);
return 0;
}
}
return 0;
}
3.mystery注解
1)效果如图
2)由图可以看出,这个程序并没有成功,因为广播组内的成员并没有收到广播消息
3)mystery尝试查找问题所在原因,但是并没有在源代码中找出错误,发表此日志,以待解决问题!
4.mystery调试
1)上网查证了下,对源代码进行了部分改动
2)广播要点:广播目的端口一定要和接收者监听的端口一致
3)在防火墙中允许广播
4)经过调试,还是未成功,不过广播和组播的原理就是这样,估计是系统的原因。纠结……