c++绑定多网卡 组播通信

多网卡时,通过绑定网卡IP地址的方式实现绑定网卡 解决组播收不到数据的问题


	server.sin_family = AF_INET;
	server.sin_port = htons(pszRemotePort); ///server的监听端口   
	server.sin_addr.s_addr = inet_addr(pszRemoteIP); ///server的地址   1

	server1.sin_family = AF_INET;
	server1.sin_port = htons(pszRemotePort); ///server的监听端口   
	server1.sin_addr.s_addr = inet_addr(pszRemoteIP); ///server的地址   1

	printf("Winsock 客户端端口: %d!\n", client.sin_port);

	if (WSAStartup(MAKEWORD(2, 2), &wsaData)) //初始化  
	{
		printf("Winsock无法初始化!\n");
		WSACleanup();
		return false;
	}
	socket1 = socket(AF_INET, SOCK_DGRAM, 0);
	printf("客户端开始创建SOCKET。\n");

	memset(&client, 0, sizeof(client));/*初始化IP多播地址为0*/
	printf("Winsock 客户端端口0: %d!\n", nLocalPort);
	client.sin_family = AF_INET;
	client.sin_port = htons(nLocalPort); //客户端端口6050  
	client.sin_addr.S_un.S_addr = htonl(INADDR_ANY);

	if (bind(socket1, (sockaddr*)&client, sizeof(sockaddr)) < 0)
	{
		printf("端口绑定失败!\n");
		return  false;
	}
	
	socket2 = socket(AF_INET, SOCK_DGRAM, 0);
	int reuse = 1;
	setsockopt(socket2, IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&reuse, sizeof(reuse));
	memset(&client1, 0, sizeof(client1));/*初始化IP多播地址为0*/
	client1.sin_family = AF_INET;
	client1.sin_port = 0;
	client1.sin_addr.s_addr = inet_addr(localIP);
	if (bind(socket2, (sockaddr*)&client1, sizeof(sockaddr)) < 0)
	{
		closesocket(socket1);
		//closesocket(socket2);
		printf("socket2端口绑定失败!\n");
		return  false;
	}

	 if_addr = inet_addr(localIP);
	//setsockopt(socket2, SOL_SOCKET,SO_DONTROUTE, (const char*)&if_addr, sizeof(if_addr));//打开路由查找功能
	setsockopt(socket1, SOL_SOCKET, SO_DONTROUTE, (const char*)&if_addr, sizeof(if_addr));
	/*设置回环许可*/
	int loop = 1;
	int err = -1;
	err = setsockopt(socket1, IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&loop, sizeof(loop));
	if (err < 0)
	{
		perror("setsockopt():IP_MULTICAST_LOOP");
		return false;
	}

	mreq.imr_multiaddr.s_addr = inet_addr(pszRemoteIP); /*广播地址*/
	//多播网卡绑定
	mreq.imr_interface.s_addr = inet_addr(localIP);
	/*将本机加入广播组*/ //IP_ADD_MEMBERSHIP
	err = setsockopt(socket1, IPPROTO_IP,12 , (char *)&mreq, sizeof(mreq));

你可能感兴趣的:(C++,UDP,c++,网络)