Sending packets to 255.255.255.255 by Java DatagramSocket fails

自作多情 提交于 2019-11-28 11:58:17

While using broadcasting you need to enable it

socket.setBroadcast(true);

Another thing is that you have to make sure that your router is configured right if the two computers are in two different nets. Broadcasts are usually by default not routed. Further if you have a router having a wirless interface and a wired interface these broadcasts may not work either if broadcasts are not enabled(There may be hardware which forward broadcasts between those two interfaces by default).

Rather than connect your DatagramSocket to the broadcast address, just construct the DatagramPacket to target it, i.e.

DatagramPacket dp = new DatagramPacket(byteArray, byteArray.length, InetAddress.getByName("255.255.255.255"), yourPortNumber);

And like magic, you've sent a broadcast. And then to catch it on the other side, just have that end listening on that port:

DatagramSocket dsock = new DatagramSocket(samePortUsedAbove);
DatagramPacket dp = new DatagramPacket(byteArray, byteArray.length);
dsock.receive(dp);
Kamahire
192.168.1.255 
  • Please check your subnet mask in your network. It might be possible that your sending machine and the receiving machine are not part of the same network.
  • Please check that the receiving machine exists in your network.
  • If there's a router in between your machines, I don't think the message will be transmitted.
ShiDoiSi

If I remember correctly, you cannot receive from broadcast-adresses, but only send to them! So on the receiving side, you must be listening on "your" IP specifically.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!