天天看點

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 , 路由多點傳播接收資料穩定, 但是同時有兩個用戶端向其發送資料,則有一方不能正常通信, 通過重新初始化程式方能通信!

[email protected]:~# 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 接口! 用于定向路由網絡多點傳播資料!

繼續閱讀