pDOTgetName
pDOTgetName

Reputation: 84

How to create a new MulticastSocket with an InetSocketAdress? I always get a BindException

I'm creating an app that needs to send messages via multi- and unicast. It works with Linux but I have some trouble getting it to work with Windows.

I got a BindException all the time and I isolated the problem in this code snippet:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;

public class Test {
    public static void main(String[] args) {

        InetSocketAddress isa = new InetSocketAddress("239.255.0.113", 1234);
        try {
            MulticastSocket mcs = new MulticastSocket(isa);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

If I run this programm I get the following Exception:

java.net.BindException: Cannot assign requested address: Cannot bind
    at java.net.TwoStacksPlainDatagramSocketImpl.bind0(Native Method)
    at java.net.AbstractPlainDatagramSocketImpl.bind(Unknown Source)
    at java.net.TwoStacksPlainDatagramSocketImpl.bind(Unknown Source)
    at java.net.DatagramSocket.bind(Unknown Source)
    at java.net.MulticastSocket.<init>(Unknown Source)
    at Test.main(Test.java:10)

The error is happening in the MulticastSocket-constructor. I have no clue how to get this to work.

Upvotes: 0

Views: 1482

Answers (2)

sfa
sfa

Reputation: 61

Maybe a bit late but perhaps for other people searching the web:
you must call the constructor that accepts the port number, then join the group (group being the InetAddress).

public class Test {
    public static void main(String[] args) {

        InetAddress ia = new InetAddress.getByName("239.255.0.113");
        try {
            MulticastSocket mcs = new MulticastSocket(1234);
            mcs.joinGroup(ia);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Don't forget to call mcs.leaveGroup(ia) when you are done.

Upvotes: 3

user207421
user207421

Reputation: 310883

Binding to the multicast address doesn't work on Windows. Bind to null, which means INADDR_ANY.

Upvotes: 2

Related Questions