Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind java.net.MulticastSocket to localhost

Tags:

java

I would like to bind a MulticastSocket to the address 127.0.0.1 (Socket should only be reachable within the current host) but with the following code example i got a

java.net.SocketException: Network is unreachable: Datagram send failed exception

Is there a way to fix the problem? Here is my code

    int port = 6677;
    InetAddress group = InetAddress.getByName("232.0.1.10");
    try(MulticastSocket s = new MulticastSocket(new InetSocketAddress(InetAddress.getByName("127.0.0.1"),port))){

        String msg = "Hello";
        s.joinGroup(group);
        DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(),group, port);
        s.send(hi);
    }
like image 780
sge Avatar asked May 06 '26 11:05

sge


1 Answers

Multicast is a little odd when compared to traditional UDP communication. The whole point is to share data on a known "channel", simultaneously, to anyone who wants access. This sharing is "signaled" to the network by using an IP address in the range 224.0.0.1 to 239.255.255.255. If you try to bind to 127.0.0.1, you just aren't doing Multicast anymore. And if you take a minute and think about it, that makes sense - you can't share the internal interface with other computers.

like image 53
JCampy Avatar answered May 08 '26 01:05

JCampy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!