简体   繁体   English

Java监听UDP端口

[英]Java Listening to a UDP port

I want to listen to a UDP port to receive the information it is transferring in wireshark it looks like this我想收听 UDP 端口以接收它在 Wireshark 中传输的信息,它看起来像这样Wireshark 过滤图像

all that I found was people creating ServerSockets but when i try that I dont get any output from the console.我发现的只是创建 ServerSockets 的人,但是当我尝试这样做时,我没有从控制台获得任何输出。

package me.xenopyax.albionmarket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {

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

        DatagramSocket serverSocket = new DatagramSocket(5056);
        byte[] receiveData = new byte[1024];
        byte[] sendData = new byte[1024];
        while(true)
            {
          DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
          serverSocket.receive(receivePacket);
          String sentence = new String( receivePacket.getData());
          System.out.println("RECEIVED: " + sentence);
          InetAddress IPAddress = receivePacket.getAddress();
          int port = receivePacket.getPort();
          String capitalizedSentence = sentence.toUpperCase();
          sendData = capitalizedSentence.getBytes();
          DatagramPacket sendPacket =
          new DatagramPacket(sendData, sendData.length, IPAddress, port);
          serverSocket.send(sendPacket);
       }

    }

}

Am I corret with using ServersSockets to listen to the port.我是否正确使用 ServersSockets 来监听端口。 or what am I doing wrong?或者我做错了什么?

As the comments state, ServerSocket is for stream-based protocol and UDP is not a stream-based protocol.正如评论所述, ServerSocket用于基于流的协议,而 UDP 不是基于流的协议。 You need to use DatagramSocket to read UDP packets.您需要使用DatagramSocket来读取 UDP 数据包。

However DatagramSocket can only be used to read UDP packets that are addressed to the current machine ... one way or another.但是DatagramSocket只能用于读取寻址到当前机器的 UDP 数据包……一种或另一种方式。

And that doesn't match what Wireshark does.这与 Wireshark 的做法不符。 In reality, Wireshark实际上,Wireshark

  • receives raw network packets (at the ISO layer 2) aka IP packets, and接收原始网络数据包(在 ISO 第 2 层)又名 IP 数据包,以及
  • often puts the NIC into "promiscuous" mode so that it can pick up packets that are not addressed to the host.通常将 NIC 置于“混杂”模式,以便它可以拾取未寻址到主机的数据包。

You can't do either of those things using the Java SE libraries, but there some third-party alternatives;你不能使用 Java SE 库来做这些事情,但有一些第三方替代品; eg例如

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM