sge
sge

Reputation: 718

How to bind java.net.MulticastSocket to localhost

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);
    }

Upvotes: 3

Views: 1313

Answers (1)

JCampy
JCampy

Reputation: 191

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.

Upvotes: 4

Related Questions