java后端获取本机的ip地址而非localhost和127.0.0.1

Posted pz_ww

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java后端获取本机的ip地址而非localhost和127.0.0.1相关的知识,希望对你有一定的参考价值。

@GetMapping("/selectIp")
    public HashMap<String, String> selectIp() {
        String ipHostAddress = "";
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress ip = (InetAddress) addresses.nextElement();
                    if (ip instanceof Inet4Address
                            && !ip.isLoopbackAddress() //loopback地址即本机地址,IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
                            && !ip.getHostAddress().contains(":")) {
                        logger.info("本机的IP = " + ip.getHostAddress());
                        ipHostAddress = ip.getHostAddress();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("ip", ipHostAddress);
        return hashMap;
    }

参考链接:https://blog.csdn.net/u010295735/article/details/74645653

 

以上是关于java后端获取本机的ip地址而非localhost和127.0.0.1的主要内容,如果未能解决你的问题,请参考以下文章

java 怎么获取本机ip地址

java如何查询本机ip地址和mac地址

js获取本机的网络IP地址

java中如何获取到本机的外网ip地址?

如何用JAVA获取本机的局域网IP地址?

Java获取本机的ip地址