Java 多播接收器不工作

标签 java multicast

我想从一个多播组和端口捕获数据包。首先,我使用 tcpdump 命令检查数据是否被捕获。

命令-

tcpdump -i <interface name> dst <multicast ip>

我在 java 中创建了一个程序,它将加入这个多播组并在控制台上打印数据。

接收者-

public class MulticastClient {

    public static void main(String args[]) throws IOException {
        MulticastSocket socket = new MulticastSocket(<port number here>);
        //socket.setInterface(InetAddress.getByName("<local interface ip address>")); // This line makes sense or not...don't know
        socket.joinGroup(InetAddress.getByName("<multicast ip here>"));

        while (true) {
            byte ab[] = new byte[583];
            DatagramPacket packet = new DatagramPacket(ab, ab.length);
            socket.receive(packet);
            System.out.println("Got packet " + Arrays.toString(ab));
        }
    }
}

此程序无法从给定的多播组和端口捕获数据包。

为了测试,我创建了一个 MulticastSockerServer,它将在一个多播组和端口上发送数据。

发件人 -

public class MulticastServer {

    public static void main(String[] args) throws Exception {

        final InetAddress group = InetAddress.getByName("<multicast group ip>");
        final int port = <port number>;

        try {
            MulticastSocket socket = new MulticastSocket(9000);
            //socket.setInterface(InetAddress.getByName("<local interface ip address>"));
            socket.joinGroup(group);

            byte[] bt = new byte[100];
            byte index = 0;
            while (true) {
                Arrays.fill(bt, (byte) index++);
                socket.send(new DatagramPacket(bt, 100, group, port));
                System.out.println("sent 100 bytes");
                Thread.sleep(1 * 1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

如果我运行这两个程序,那么它将按我预期的那样工作,数据在接收端被捕获。那为什么receiver only不能从不同的组播组ip和端口抓取数据呢?

任何建议都会被采纳。

最佳答案

我清楚了,我发现了为什么 java 客户端无法获取数据。实际上 tcpdump 命令是 -

tcpdump -i <interface name> dst <multicast ip>

此命令将捕获目标地址由命令(多播 ip)给出的任何数据包(即,无论是 UDP 还是 PGM)。

Java 客户端只会捕获 UDP 数据包,不会捕获 PGM 数据包。在我的本地网络上,只有 PGM 数据包可用,因此 tcpdump 命令将为我们提供数据,但 Java 客户端不会收到任何数据。

如果你想捕获 PGM 数据包,那么你需要使用以下之一 -

  1. 使用 JnetPcap 库捕获/读取任何(即 UDP 或 PGM)数据包。
  2. 使用 Javapgm 库只捕获 pgm 数据包。
  3. 使用dumpcap 捕获数据包并将其存储在pcap 文件中。

希望对您有所帮助。

关于Java 多播接收器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45190038/

相关文章:

java - 如何在 JAXB 中映射已有的 java bean

android - 发送组播 UDP 并等待响应

android - 多播 - 没有这样的设备

c++ - 使用use_future的Boost Asio async_send_to多播不起作用

c++ - Ubuntu C++ 多播双留组消息

c++ - 在具有多个接口(interface)的linux主机上接收多播

java - 在 Jsp 中显示来自类的对象列表

Java/Kotlin : Tokenize a string ignoring the contents of nested quotes

java - 如何在不使用 SoapHandler 的情况下通过 jaxb 将自定义 header 添加到 SOAP 请求

java - 检查目录是否注册到任何观察者服务?