Java UDP multicast, determine which group sent the packet

I am creating an application where there is a specific thread (MulticastListenerThread) that has a MulticastSocket and listens for UDP packets (datagrams) sent to the multicast group that the socket also listens on.

It works. I can join a multicast group, send a message to this group and receive it through MulticastSocket.

However, I would like to determine, from the perspective of the recipient, from which multicast group it received the packet. The following code gives me the address of the package creator, not the multicast group:

DatagramPacket packet = new DatagramPacket(buf, buf.length); mlcSenderSocket.receive(packet); String src_addr = packet.getAddress().getHostAddress(); 

The code for sending the package is as follows:

 InetAddress address = InetAddress.getByName(dest); packet = new DatagramPacket(payload, payload.length, address, mlcEventPort); LLog.out(this,"[NC] MLC packet Sent to ev port MLC " + mlcEventPort + " and to addr " + address); mlcSenderSocket.send(packet); 

Is it even possible to determine which group sent the packet?

Edit:

It seems to be impossible. As for the performance impact (I work on IoT devices), would I make the socket for each multicast group (and therefore the listener flow for each group) viable? Potentially, many groups can be combined (in terms of tens or hundreds even). If this is viable, then I just need to save the attached group address somewhere manually and access it as needed. Suggestions for other works are welcome!

+5
source share
2 answers

No group sent a packet. A socket on a specific IP address sent a packet, and the source IP address is available in DatagramPacket . Multicast packets do not come from multicast groups; they are addressed to multicast groups.

+2
source

Yes, it’s true that you can join a MulticastSocket for several groups, for example:

 InetAddress group; MulticastSocket s=new MulticastSocket(12345); NetworkInterface ni=NetworkInterface.getByName("eth1"); group=InetAddress.getByName("239.255.10.10"); s.joinGroup(new InetSocketAddress(group,12345),ni); group=InetAddress.getByName("239.255.10.11"); s.joinGroup(new InetSocketAddress(group,12345),ni); 

Then you get datagrams as follows:

 DatagramPacket datagram=s.receive(datagram); 

Unfortunately, there is no java API call in the DatagramPacket object that allows you to determine which of the two groups was configured by the sender, all you can get is the IP address of the network interface on which it was received (from the socket) and Sender IP address (from datagram).

In order to achieve what you want to do, you will need to create several MulticastSocket objects and listen to one group on one socket. You can use your own streams or NIO to listen to them all at the same time.

0
source

Source: https://habr.com/ru/post/1209524/


All Articles