我的任务是从传感器设备获取数据。通过Wireshark,我可以捕获如下信息:
它将信息从 10.13.1.113 发送到 224.0.2.2(多播地址)。源端口 42402,目标端口 42102)。
我使用 Ubuntu 20.04 并使用下面的简单代码
int main(int argc, char* argv[])
{
char* lcAddrIp = "10.13.1.102";
char* mcAddrIp = "224.0.2.2";
unsigned short mcPort = 42102;
struct sockaddr_in mcAddr;
memset(&mcAddr,0,sizeof(mcAddr));
// establish socket
int sockfd;
if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))<0)
{
printf("socket established failed, exit!");
return -1;
}
// multicast configure
mcAddr.sin_family = AF_INET;
mcAddr.sin_addr.s_addr = inet_addr(mcAddrIp);
mcAddr.sin_port = htons(42102);
unsigned int mcAddrLen = sizeof(mcAddr);
if (bind(sockfd, (struct sockaddr *)&mcAddr, mcAddrLen) <0)
{
printf("Can't bind socket to local port. exit\n");
return -1;
}
// Set multicast
ip_mreq mreq;
memset(&mreq, 0, sizeof(struct ip_mreq));
mreq.imr_multiaddr.s_addr = inet_addr(mcAddrIp);
mreq.imr_interface.s_addr = inet_addr(lcAddrIp);
if (setsockopt (sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&mreq, sizeof(mreq)) < 0)
{
printf("SET IP_ADD_MEMBERSHIP error\n");
close(sockfd);
return -1;
}
unsigned int iBufLen = sizeof(char) * MAX_LONG_FRAME;
char *pcMutilRecvBuf = NULL;
pcMutilRecvBuf = (char *)malloc(iBufLen);
int recv_len;
while (1)
{
if (recv_len = recvfrom(sockfd, pcMutilRecvBuf, iBufLen, 0, (sockaddr*)&mcAddr, (socklen_t*)&mcAddrLen)<0)
{
printf("Received Failed!");
return -1;
}
printf("Received %d bytes from %s: ", recv_len,
inet_ntoa(mcAddr.sin_addr));
}
}
我将本地计算机卡 enp61s0 设置为 IP 10.13.1.102,网络掩码 255.255.0.0。代码停留在recvfrom()函数上,无法获取任何数据。
我已将 224.0.2.2 添加到路由协议中route add -net 10.13.1.113 netmask 255.255.255.255 enp61s0
。