java.net.SocketException: 不是多播地址

java.net.SocketException: Not a multicast address

我正在使用 MulticastSocket,每当我尝试加入一个组时,当我是 运行 "localhost" ip 上的组时,它永远不会工作。但是,我发现这篇文章 http://lycog.com/programming/multicast-programming-java/ 指出范围应介于 224.0.0.1 和 239.255.255.254 之间。当我从该 IP 中创建一个 InetAddress 并加入该组时,它起作用了。请解释为什么这是必要的。

示例:

InetAddress group = InetAddress.getByName("localhost");
int port = 8888;
MulticastSocket socket = new MulticastSocket(port);
socket.joinGroup(group);

//抛出

Unable to connect to host:localhost on port:8888
java.net.SocketException: Not a multicast address

有效示例:

InetAddress group = InetAddress.getByName("224.0.0.1");
int port = 8888;
MulticastSocket socket = new MulticastSocket(port);
socket.joinGroup(group);

一切都与标准有关。只是 wiki article 中关于多播地址的一小段:

IPv4 multicast addresses are defined by the leading address bits of 1110, originating from the classful network design of the early Internet when this group of addresses was designated as Class D. The Classless Inter-Domain Routing (CIDR) prefix of this group is 224.0.0.0/4. The group includes the addresses from 224.0.0.0 to 239.255.255.255.

此外,对于 MulticastSocket

javadoc 中的说法几乎相同

A multicast group is specified by a class D IP address and by a standard UDP port number. Class D IP addresses are in the range 224.0.0.0 to 239.255.255.255, inclusive. The address 224.0.0.0 is reserved and should not be used.

所以,是的,当您尝试加入组地址超出此范围的多播组时(例如本地主机 127.0.0.1),您会遇到此异常。