Java,DatagramPacket接收,如何确定本地ip接口

Igo*_*lac 8 java datagram

这是绑定到所有ip接口和特定udp端口的简单情况:

int bindPort = 5555;  // example, udp port number
DatagramSocket socket = new DatagramSocket(bindPort);

byte[] receiveData = new byte[1500];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

...

socket.receive(receivePacket);
Run Code Online (Sandbox Code Playgroud)

我怎么知道我收到了哪个ip接口的数据包?

我可以看到有getSocketAddress():

获取此数据包发送到或来自的远程主机的SocketAddress(通常是IP地址+端口号).

但是返回远程ip +端口.我想知道本地ip(在这个例子中本地端口是5555).

有没有可能与标准.Java库?

Dan*_*der 5

我知道这个问题。为了阐明这个目的:您通过 UDP 收到一个数据包(通常是某种发现实现)并希望返回一个类似的回答(“亲爱的客户,请从http://<wtf-is-my-ip>:8080/thefile.txt”下载文件)。我的机器有三个 IP:127.0.0.1、192.168.xx 和 10.xxx,目标是找出远程客户端将 UDP 数据包发送到 192.168.xx 并且这必须是也适用于另一个连接的 IP .

weupnp 项目中,我发现了以下代码,它并不完美,但对我有用

    private InetAddress getOutboundAddress(SocketAddress remoteAddress) throws SocketException {
        DatagramSocket sock = new DatagramSocket();
        // connect is needed to bind the socket and retrieve the local address
        // later (it would return 0.0.0.0 otherwise)
        sock.connect(remoteAddress);

        final InetAddress localAddress = sock.getLocalAddress();

        sock.disconnect();
        sock.close();
        sock = null;

        return localAddress;
    }

//DatagramPacket receivePacket;
socket.receive(receivePacket);
System.out.print("Local IP of this packet was: " + getOutboundAddress(receivePacket.getSocketAddress()).getHostAddress);
Run Code Online (Sandbox Code Playgroud)

如果您在同一网络中有多个 IP 或由于某些高级路由配置,代码可能会返回错误的 IP。但到目前为止,它是我能找到的最好的,并且对于大多数情况来说已经足够了。