绑定到“0.0.0.0”时,如何找到我的Java ServerSocket绑定到的实际接口IP地址?

When binding to "0.0.0.0", how to find the actual interface IP address that my Java ServerSocket was bound to?

所以我将 Java ServerSocket 绑定到 0.0.0.0。假设我的机器有 3 个网络接口,每个接口都有自己的 IP 地址。现在我想以编程方式发现我的客户端可以用来连接到我最近创建的 ServerSocket 的 IP 地址。呼叫:

serverSocket.getLocalSocketAddress()

serverSocket.getInetAddress()

Returns“0.0.0.0”,这当然是我不想要的

有什么想法吗?

您无法从 ServerSocket 获取该信息。您必须使用 NetworkInterface.getNetworkInterfaces() and NetworkInterface.getInetAddresses().

单独枚举实际接口

根据 Java 文档中的 Listing Network Interface Addresses

One of the most useful pieces of information you can get from a network interface is the list of IP addresses that are assigned to it. You can obtain this information from a NetworkInterface instance by using one of two methods. The first method, getInetAddresses(), returns an Enumeration of InetAddress. The other method, getInterfaceAddresses(), returns a list of java.net.InterfaceAddress instances. This method is used when you need more information about an interface address beyond its IP address. For example, you might need additional information about the subnet mask and broadcast address when the address is an IPv4 address, and a network prefix length in the case of an IPv6 address.

The following example program lists all the network interfaces and their addresses on a machine:

import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;

public class ListNets {

    public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            out.printf("InetAddress: %s\n", inetAddress);
        }
        out.printf("\n");
     }
}  

The following is sample output from the example program:

Display name: TCP Loopback interface
Name: lo
InetAddress: /127.0.0.1

Display name: Wireless Network Connection
Name: eth0
InetAddress: /192.0.2.0