码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-11-16 13:09:14      阅读:9      评论:0      收藏:0      [点我收藏+]

标签:mapping   trace   eof   detail   exce   instance   style   tps   app   

@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

标签:mapping   trace   eof   detail   exce   instance   style   tps   app   

原文地址:https://www.cnblogs.com/pzw23/p/13947322.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!