Java 获取本机IP

windows

String hostAddress = Inet4Address.getLocalHost().getHostAddress();

linux and windows

获取第一个非环回ip

String hostAddress = null;
Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
    NetworkInterface networkInterface = networkInterfaces.nextElement();
    if (networkInterface.getName().equals("lo")) {
        continue;
    }
    Enumeration inetAddresses = networkInterface.getInetAddresses();
    while (inetAddresses.hasMoreElements()) {
        InetAddress inetAddress = inetAddresses.nextElement();
        if (inetAddress != null && inetAddress instanceof Inet4Address) {
            hostAddress = inetAddress.getHostAddress();
            break;
        }
    }
    if (hostAddress != null) {
        break;
    }
}

你可能感兴趣的:(java)