【问题标题】:No reply to UDP broadcast, only unicast没有回复UDP广播,只有单播
【发布时间】:2014-05-11 01:30:14
【问题描述】:

在我的 Android 应用程序中,我正在向地址 255.255.255.255、端口 6400 发送 UDP 广播。我使用 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” - 仍然不起作用。

【问题讨论】:

  • 我偶尔会遇到这种情况。有时网络会丢弃数据包或不会转发它。根据我运行它的网络,有时它可以工作,有时它不会
  • 您的网络路由器必须允许多播/广播才能正常工作...
  • @GermannArlington - 路由器已经允许这样做。
  • 我也可以假设您的 IP 在同一个网络上吗?您是否尝试过反复/频繁地广播?
  • @GermannArlington - 当然。

标签: java android udp broadcast


【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 2014-12-04
    • 2010-10-15
    相关资源
    最近更新 更多