0

I'm trying to send and receive UDP broadcast messages.

At the beginning it didn't work, but after I found out that I had to use a wildcard address on the receiver side (0.0.0.0). So it worked.

But I would like to understand why do I have to use a wildcard address? It binds to all network interfaces, isn't there a way to bind to a specific address and still continuing to receive broadcast?

Sender

InetAddress localHOst = InetAddress.getByName("192.168.1.1");    

DatagramSocket socket = new DatagramSocket(50000, localHost);
socket.setBroadcast(true);

byte[] data = msg.getBytes();
InetAddress dest = InetAddress.getByName("192.168.255.255");
DatagramPacket packet = new DatagramPacket(data, data.length, dest, 49152);
socket.send(packet);
socket.close();

Receiver

InetAddress broadcastWildcard = InetAddress.getByName("0.0.0.0");
DatagramSocket socket = new DatagramSocket(49152, broadcastWildcard);
byte[] data = null;
while(true) {
    data = new byte[Settings.MSG_SIZE];
    DatagramPacket packet = new DatagramPacket(data, data.length);
    socket.receive(packet);
}
pnuts
  • 58,317
  • 11
  • 87
  • 139
zer0uno
  • 7,521
  • 13
  • 57
  • 86
  • Can you provide an [MCVE](http://stackoverflow.com/help/mcve)? – Ortomala Lokni Oct 27 '15 at 12:28
  • first, what system are you on? and I don't know what the variable localhost is, or Settings.RECV_PORT. Try this for creating your socket "new DatagramSocket(50000, InetAddress.getLocalHost());" – WalterM Oct 27 '15 at 13:48
  • Gosh...the problem isn't the code. I don't mind it. I am simply asking about the wildcard address `0.0.0.0` – zer0uno Oct 27 '15 at 13:51
  • 1
    @welcome all programmers say their code isn't a problem. what are inside those variables? – WalterM Oct 27 '15 at 13:55
  • well from the looks of it you're not sending to the same port you're listening on? try sending to 49152 – WalterM Oct 27 '15 at 14:00
  • @WalterM It was just a copy-paste error. However there' s no need to study my code, I tried it, it worked. I sent "AAA" message from one PC and the second received "AAA" there is no way to worry about that. That's not the point of the question – zer0uno Oct 27 '15 at 14:02
  • 1
    well the only assumption I can make is that you're using the wrong broadcast address which could be wrong since I don't know anything about your network. instead of 192.168.255.255 use 192.168.1.255. I threw together a simple test and I was able to bind to the local address and receive broadcast on windows. – WalterM Oct 27 '15 at 14:13

0 Answers0