MulticastSocket 确定收到的消息是否是单播的

MulticastSocket determine if message received was unicast

我的服务器目前能够发送和接收多播数据包。我正在添加接收和发送单播数据包的功能。所以我创建了 "DatagramSocket uniRecv" 和 "DatagramSocket uniSend" 来模仿多播的方式。问题是当我收到一个数据包时,我需要一种方法来判断它是多播还是单播。我认为 "multiRecv.receive(packet)" 只适用于多播数据包,但显然它也适用于单播数据包。有没有办法告诉在执行 .receive(packet) 之前或之后检测它是哪种数据包?

我需要知道,因为当我发出响应时,必须使用与接收到的相同的方法来完成。因此,如果我收到单播,我需要发送单播,如果我收到多播,我需要发送多播。

另外,MulticastSocket 也可以发送单播消息吗?

编辑: 尽管接受的 post 是正确的,但我还是找到了解决方法。通过强制服务器向我发送数据包,为单播和多播使用不同的端口,我能够通过使用 packet.getPort().

找出它是哪个端口

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?

不在 Java 中。在 BSD 套接字 API 中有一个检索数据报目标地址的功能,但在 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.

抱歉,无法在 Java 中为您提供帮助。

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

是的。并进一步注意,您不需要 MulticastSocket 发送 多播,并且您不需要为了发送任何一个而加入该组。