1、问题:之前使用InetAddress.getLocalHost().getHostAddress()时,在开发机测试可以得到192.168.0.18这样的IP。但部署到linux服务器以后,

这个值却变成了127.0.0.1,如何得到真正的IP地址?

2、方案:

public static InetAddress getCurrentIp() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) networkInterfaces.nextElement();
                Enumeration<InetAddress> nias = ni.getInetAddresses();
                while (nias.hasMoreElements()) {
                    InetAddress ia = (InetAddress) nias.nextElement();
                    if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address) {
                        return ia;
                    }
                }
            }
        } catch (SocketException e) {
        }
        return null;
    }

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-15
  • 2021-12-04
  • 2021-12-21
  • 2021-12-09
猜你喜欢
  • 2021-09-14
  • 2022-12-23
  • 2021-08-04
  • 2021-12-19
  • 2021-12-04
  • 2021-11-11
  • 2021-08-18
相关资源
相似解决方案