首页 文章

没有回复UDP广播,只有单播

提问于
浏览
2

在我的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时,我只能在我的应用程序中收到回复 . 我've also tried 2625144 (broadcast on my local subnet) instead of 2625145 - still doesn'工作 .

1 回答

  • 1

    我发现了这个问题 .

    我没有将目标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);
    

相关问题