我需要通过一个以太网连接从两个源接收多播数据,即224.0.31.132端口14384和224.0.31.130端口14382。
首先,我尝试与端口14384绑定,然后加入两个IP地址,但我仅从224.0.31.132获得数据。
如果我与14382绑定并同时加入两者,则只能从224.0.31.130获得数据。
因此,然后我尝试创建两个套接字,将第一个套接字绑定到14384并加入224.0.31.132,然后将第二个套接字绑定到14382并加入224.0.31.130。
当我这样做时,我从224.0.31.130获得了数据,但没有从224.0.31.132获得数据,并且ip maddr show显示到224.0.31.132的联接显然已被第二个套接字的设置删除。
如何在单个eth端口上从这两个来源接收数据?
以下是第一种方法的代码:
// Activity class
Intent intent = new Intent(this, DetailsActivity.class);
// multiple instances can be launched without this line
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivityForResult(intent, REQUEST_CODE_DETAILS);
// AndroidManifest.xml
<activity
android:name=".DetailsActivity"
android:launchMode="singleTop"/>
以下是结果输出:
/* Create a datagram socket on which to receive. */
int sd = socket(AF_INET, SOCK_DGRAM, 0);
if(sd < 0)
{
perror("Opening datagram socket error");
exit(1);
}
else
cout<<"Opening datagram socket....OK."<<endl;
/* Enable SO_REUSEADDR to allow other */
/* applications to receive copies of the multicast datagrams. */
{
int reuse = 1;
if(setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse)) < 0)
{
perror("Setting SO_REUSEADDR error");
close(sd);
exit(1);
}
else
cout<<"Setting SO_REUSEADDR...OK."<<endl;
}
/* Enable SO_REUSEPORT to allow multiple uses of receive port */
{
int reuse = 1;
if(setsockopt(sd, SOL_SOCKET, SO_REUSEPORT, (char *)&reuse, sizeof(reuse)) < 0)
{
perror("Setting SO_REUSEPORT error");
close(sd);
exit(1);
}
else
cout<<"Setting SO_REUSEPORT...OK."<<endl;
}
/* Bind to the proper port number with the IP address */
/* specified as INADDR_ANY. */
struct sockaddr_in localSock;
memset((char *) &localSock, 0, sizeof(localSock));
localSock.sin_family = AF_INET;
localSock.sin_port = htons(14384);
localSock.sin_addr.s_addr = INADDR_ANY;
if(bind(sd, (struct sockaddr*)&localSock, sizeof(localSock)))
{
perror("Binding datagram socket error");
close(sd);
exit(1);
}
else
cout<<"Binding datagram socket...OK."<<endl;
/* Join the multicast groups on the local nic interface. */
struct ip_mreq group;
group.imr_interface.s_addr = inet_addr("0.0.0.0");
int ipcount = stoi(getSetup("mcstcount"));
while(ipcount>0)
{
string which = "listenip" + to_string(ipcount);
cout<<"listen to "<<getSetup(which.c_str())<<endl;
group.imr_multiaddr.s_addr = inet_addr(getSetup(which.c_str()).c_str());
ipcount--;
if(setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&group, sizeof(group)) < 0)
{
perror("Adding multicast group error");
close(sd);
exit(1);
}
else
cout<<"Adding multicast group...OK."<<endl;
}
// process Mdp feed
while( !stop_cond )
{
/* Read from the socket. */
const int DBUFSZ = 5000;
uint8_t databuf[DBUFSZ];
int datalen;
datalen=read(sd, databuf, DBUFSZ);
if(datalen < 0)
{
perror("Reading datagram message error");
close(sd);
exit(1);
}
//process data
}
但是数据仅来自224.0.31.132。
答案 0 :(得分:0)
结论是不能使用单个套接字,因为有多个端口可以接收。返回到第二种方法,使用多个插座。一切正常,不知道第一次出什么问题。