[英]No reply to UDP broadcast, only unicast
在我的Android应用中,我正在将UDP广播发送到地址255.255.255.255的端口6400。我使用PC程序Packet Sender充当自动发送回复的UDP服务器。
当我在Android应用程序中收听此回复时,它永远不会收到回复。 如果我不将数据包发送到255.255.255.255,而是发送到PC的特定IP地址,则只能收到答复。
private String udpDestinationAddress = "255.255.255.255";
private int udpDestinationPort = 6400;
private int udpTimeoutMs = 5000;
private String udpData = "test";
DatagramSocket socket;
socket = new DatagramSocket(12345);
socket.setBroadcast(true);
socket.setSoTimeout(udpTimeoutMs);
socket.connect(InetAddress.getByName(udpDestinationAddress), udpDestinationPort);
// send part
byte[] data = udpData.getBytes();
int length = data.length;
DatagramPacket packet = new DatagramPacket(data, length);
socket.send(packet);
// receive part
byte[] buffer = new byte[1000];
// Initialize the packet
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
// Receive the packet
socket.receive(packet); // it timeouts here (if timeout=0, then it hangs here forever)
// Get the host IP
String hostIP = packet.getAddress().toString().replace("/", "");
在PC程序中,我将其设置为自动(使用另一个随机字符串)回复端口6400上的数据包。这与我测试过的其他应用程序(各种UDP测试Android应用程序)配合得很好。 但是,我的应用似乎无法得到回复。
将udpDestinationAddress
设置为PC的特定IP时,我只能在我的应用程序中得到答复。 我还尝试了“ 192.168.5.255”(在本地子网上广播),而不是“ 255.255.255.255”-仍然无法正常工作。
我发现了问题。
我没有将目标IP和端口绑定到socket
,而是需要将其绑定到packet
。
因此,代替:
socket.connect(InetAddress.getByName(udpDestinationAddress), udpDestinationPort);
...
DatagramPacket packet = new DatagramPacket(data, length);
...改用它:
InetAddress addr = InetAddress.getByName("255.255.255.255");
DatagramPacket packet = new DatagramPacket(udpData.getBytes(), udpData.length(), addr, udpDestinationPort);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.