openwrt之应用组播multicast发送接收

组播基本介绍

根据以上介绍 , 我们写出组播接收程序! 

应用背景

wifi board 连接上级路由器,而后通过pc网络调试助手向其发送组播数据 ! 组播地址ip 定位: 224.0.1.100, 在上面的理论介绍中,该地址为:预留多播地址:在224.0.1.0~238.255.255.255之间,可用于全球范围(如Internet)或网络协议

int multicast_server_init(void)
{
	int err = -1;
	char buf[100]={0};

	struct sockaddr_in local_addr;              /*本地地址*/
	struct sockaddr_in peer_addr; 

	

	struct stConfig *config = config_list();

	ULOG_INFO("WIFI option : %s,%d\n",config->addr,config->port);



	multicast_server_fd = socket(AF_INET, SOCK_DGRAM, 0);     /*建立套接字*/
	if (multicast_server_fd == -1)
	{
		perror("socket()");
		return -1;
	}  

	/*初始化地址*/
	memset(&local_addr, 0, sizeof(local_addr));
	local_addr.sin_family = AF_INET;
	local_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	//local_addr.sin_port = htons(MCAST_PORT);
	local_addr.sin_port = htons(config->port);
	
	/*设置回环许可*/
	int loop = 1;
	err = setsockopt(multicast_server_fd,IPPROTO_IP, IP_MULTICAST_LOOP,&loop, sizeof(loop));
	if(err < 0)
	{
		perror("setsockopt():IP_MULTICAST_LOOP");
		close(multicast_server_fd);
		return -3;
	}
	
    bool bReuseaddr = true;
	err = setsockopt(multicast_server_fd,SOL_SOCKET, SO_REUSEADDR,&bReuseaddr, &bReuseaddr);
	if(err < 0)
	{
		perror("setsockopt():SOL_REUSEADDR");
		close(multicast_server_fd);
		return -3;
	}

	/*绑定socket*/
	err = bind(multicast_server_fd,(struct sockaddr*)&local_addr, sizeof(local_addr)) ;
	if(err < 0)
	{
		perror("bind()");
		close(multicast_server_fd);
		return -2;
	}
	
	struct ip_mreq mreq;                                    /*加入多播组*/
	//mreq.imr_multiaddr.s_addr = inet_addr(MCAST_ADDR); /*多播地址*/
	mreq.imr_multiaddr.s_addr = inet_addr(config->addr); /*多播地址*/
	mreq.imr_interface.s_addr = htonl(INADDR_ANY); /*网络接口为默认*/

membership:
    memset(buf,0x0,100);
    //通过wlan0-1路由数据,允许所有组播数据
	sprintf(buf,"route add -net 224.0.1.100 netmask 255.255.255.255 wlan0-1");
	system(buf);

	/*将本机加入多播组*/
	err = setsockopt(multicast_server_fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,&mreq, sizeof
			(mreq));
	if (err < 0)
	{
		perror("setsockopt():IP_ADD_MEMBERSHIP");
		//return -4;
		sleep(2);
		goto membership;
	}

	return 0;
}

但该程序运行后,并不能友好的接收数据;  而后加入/usr/sbin/igmpproxy /var/etc/igmpproxy.conf , 路由组播接收数据稳定, 但是同时有两个客户端向其发送数据,则有一方不能正常通信, 通过重新初始化程序方能通信!

root@Leedarson:~# cat /etc/config/igmpproxy 
config igmpproxy
	option quickleave 1

config phyint wan
	option network wwan
	option direction upstream
	list altnet 192.168.1.0/24

config phyint lan
	option network lan
	option direction downstream

其中,upstream 、 downstream 在我的项目中对应wlan0-1(station mode), br-lan 接口! 用于定向路由网络组播数据!

你可能感兴趣的:(openwrt,openwrt,multicast,组播,linux)