javasocketsmulticastunicast

MulticastSocket determine if message received was unicast


My server currently is able to send and receive multicast packets. I am adding the ability to also receive and send unicast packets. So I created "DatagramSocket uniRecv" and "DatagramSocket uniSend" to mimic the way multicast was done. The problem is that when I receive a packet I need a way to tell if it is multicast or unicast. I thought "multiRecv.receive(packet)" would only work on multicast packets, but apparently it can also work on unicast packets. Is there a way to tell either before or after doing .receive(packet) to detect which kind of packet it is?

I need to know because when I send out a response it has to be done using the same method as it was received. So if I receive unicast I need to send unicast and if I receive multicast I need to send multicast.

On another note, can a MulticastSocket also send a unicast message?

EDIT: Although the accepted post is true, I was able to find a work around. By forcing the server sending the packet to me, to use different ports for unicast and multicast, I was able to figure out which one it was by using packet.getPort().


Solution

  • I need a way to tell if it is multicast or unicast. I thought "multiRecv.receive(packet)" would only work on multicast packets, but apparently it can also work on unicast packets. Is there a way to tell either before or after doing .receive(packet) to detect which kind of packet it is?

    Not in Java. In the BSD Sockets API there is a feature to retrieve the target address of a datagram, but it isn't implemented in Java.

    I need to know because when I send out a response it has to be done using the same method as it was received. So if I receive unicast I need to send unicast and if I receive multicast I need to send multicast.

    Sorry, can't help you in Java.

    On another note, can a MulticastSocket also send a unicast message?

    Yes. And further note that you don't need a MulticastSocket to send multicasts, and you don't need to join the group just to send either.