DatagramSocket侦听广播地址

DatagramSocket侦听广播地址

本文介绍了Java DatagramSocket侦听广播地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的测试类,用于侦听Eth并接收所有 UDP 数据包,这些数据包转到端口 5001

I have written the simple test class which is meant to listen on Eth and receive all UDP packets, which go to port 5001:

public class Main {

  public static void main(String[] args) throws SocketException, UnknownHostException, IOException {
    DatagramSocket socket = new DatagramSocket(5001, InetAddress.getByName("255.255.255.255"));
    socket.setBroadcast(true);
    System.out.println("Listen on " + socket.getLocalAddress() + " from " + socket.getInetAddress() + " port " + socket.getBroadcast());
    byte[] buf = new byte[512];
    DatagramPacket packet = new DatagramPacket(buf, buf.length);
    while (true) {
      System.out.println("Waiting for data");
      socket.receive(packet);
      System.out.println("Data received");
    }
  }
}

它不再起作用了。它打印出等待数据并且永远不会继续。 tcpdump告诉我,UDP广播包来了。我究竟做错了什么?非常感谢。

It does not work anymore. It prints out Waiting for data and never continue. tcpdump shows me, that UDP broadcast packets come. What am I doing wrong? Thank you much.

推荐答案

接收方无法收听广播地址。

Receiver can't listen on a broadcast address.

广播地址用于发送者 - 发送者可以发送一个255.255.255.255:5001作为目的地的数据包,并且监听子网中该端口的所有接收者都会收到它。但是没有办法创建一个可以接收所有UDP数据包的接收器。

Broadcast address is for senders - sender can send a packet with 255.255.255.255:5001 as a destination, and all receivers listening that port in a subnet would receive it. But there is no way to create a receiver that can receive "all UDP packets".

如果您已有广播发送者并希望收到其数据包,则需要收听通配符地址:

If you already have a broadcast sender and want to receive its packets, you need to listen on a wildcard address instead:

DatagramSocket socket = new DatagramSocket(5001, InetAddress.getByName("0.0.0.0"));

这篇关于Java DatagramSocket侦听广播地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 22:03