UDP:为两个不同的多播流监听同一个端口 [英] UDP: Listening to the same port for two different multicast streams
问题描述
我需要使用同一个端口监听 2 个不同的多播组.Program A
将从 230.0.0.1
监听,Program B
从 230.0.0.2
监听.两个多播组都使用相同的 port 2000
,我无法控制它.
I need to listen to 2 different multicast groups using the same port. Program A
will listen from 230.0.0.1
and Program B
from 230.0.0.2
. Both multicast groups use the same port 2000
and I have no control over it.
当我运行我的程序时,我在每个程序中都接收到多播流,即在 230.0.0.1
和 230.0.0.2
上广播的数据包.我怀疑问题出在公共端口上.这是我用来订阅多播的代码:
When I run my programs I receive both multicast streams in each program, that is both the data packets broadcasted on 230.0.0.1
and 230.0.0.2
. I suspect the problem is due to the common port. This is the code I am using to subscribe to the multicast:
if( (sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0 ) {
perror("socket");
return -1;
}
if( setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0 ) {
perror("setsockopt SO_REUSEADDR");
return -1;
}
memset(&in_addr, 0, sizeof(in_addr));
in_addr.sin_family = AF_INET;
in_addr.sin_addr.s_addr = htonl(INADDR_ANY);
in_addr.sin_port = htons(2000);
if( bind(sd, (struct sockaddr*)&in_addr, sizeof(in_addr)) < 0 ) {
perror("bind");
return -1;
}
memset(&req, 0, sizeof(req));
inet_aton(intfc_ip, &req.imr_interface);
inet_aton("230.0.0.1", &req.imr_multiaddr);
if( setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &req, sizeof(req)) < 0 ) {
perror("setsockopt IP_ADD_MEMBERSHIP");
return -1;
}
recv()...
如何过滤每个节目中的特定多播组?
How can I filter a specific multicast group in each program?
推荐答案
如果你改变了
in_addr.sin_addr.s_addr = htonl(INADDR_ANY);
到
inet_aton(<your wanted IP address>, &in_addr.sin_addr.s_addr);
你可以取得更大的成功.
you could have more success.
(如果您更改程序以使用 getaddrinfo()
,你让它永不过时.)
(And if you change your program to work with getaddrinfo()
, you make it future-proof.)
这篇关于UDP:为两个不同的多播流监听同一个端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!