erikvimz
erikvimz

Reputation: 5476

Java - SocketException: Not a multicast address

I have multiple servers on my network that all send out a broadcast message. With the following client I am trying to capture all the broadcast messages from all servers. The sending part works fine(not included in this post), but my receiving part doesn't work... I keep getting "SocketException: Not a multicast address", what am I doing wrong?

public static String[] capture(int port) { // port is always 63332
    ArrayList<String> clients = new ArrayList<>();

    InetAddress address = Utilities.getBroadcastAddress(); // I get "/192.168.2.255" here

    MulticastSocket socket = null;

    try {
        socket = new MulticastSocket(port);
        socket.setSoTimeout(2000);
        socket.joinGroup(address); // this part throws the exception

        DatagramPacket packet;
        byte[] packetContent;

        while (true) {
            packetContent = new byte[1024];
            packet = new DatagramPacket(packetContent, packetContent.length);

            try {
                socket.receive(packet);

                String client = packet.getAddress() + ":" + packet.getPort();

                clients.add(client);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if(socket != null) {
        try {
            socket.leaveGroup(address);
        } catch(IOException e) {
            e.printStackTrace();
        }

        socket.close();
    }

    return clients.toArray(new String[clients.size()]);
}

Upvotes: 1

Views: 1171

Answers (1)

user207421
user207421

Reputation: 311055

You are confusing broadcasting with multicasting. A multicast address is not a broadcast address. Make up your mind which it is that you're doing. If you're receiving multicasts, you need to join the correct multicast address, whatever it is. If you're receiving broadcasts, don't join anything.

Upvotes: 2

Related Questions