[英]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.