• Java实现Ip地址获取


    一、两种实现方式

    package com.lyp;
    
    import org.apache.commons.lang3.ObjectUtils;
    
    import java.net.*;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.List;
    import java.util.Optional;
    
    /**
     * 获取本机IP 地址
     *
     */
    public class IpUtils {
    
        public static void main(String[] args) throws SocketException, UnknownHostException {
            System.out.println("传统方式-----------hostAddress = " +getTraditionIp());
            System.out.println( "新方式-----------hostAddress = "+IpUtils.getLocalIp4Address().get().toString().replaceAll("/",""));
        }
    
    
        /**
         * 传统方式,非常简单直接通过InetAddress获取,但不准确获取的为虚拟ip
         * @throws UnknownHostException
         */
        public static String getTraditionIp() throws UnknownHostException {
    
            InetAddress localHost = InetAddress.getLocalHost();
            String hostAddress = localHost.getHostAddress();
            String hostName = localHost.getHostName();
            return hostAddress;
        }
    
    
    
        /*
         * 获取本机所有网卡信息   得到所有IP信息
         * @return Inet4Address>
         */
        public static List getLocalIp4AddressFromNetworkInterface() throws SocketException {
            List addresses = new ArrayList<>(1);
    
            // 所有网络接口信息
            Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
            if (ObjectUtils.isEmpty(networkInterfaces)) {
                return addresses;
            }
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                //滤回环网卡、点对点网卡、非活动网卡、虚拟网卡并要求网卡名字是eth或ens开头
                if (!isValidInterface(networkInterface)) {
                    continue;
                }
    
                // 所有网络接口的IP地址信息
                Enumeration inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    // 判断是否是IPv4,并且内网地址并过滤回环地址.
                    if (isValidAddress(inetAddress)) {
                        addresses.add((Inet4Address) inetAddress);
                    }
                }
            }
            return addresses;
        }
    
        /**
         * 过滤回环网卡、点对点网卡、非活动网卡、虚拟网卡并要求网卡名字是eth或ens开头
         *
         * @param ni 网卡
         * @return 如果满足要求则true,否则false
         */
        private static boolean isValidInterface(NetworkInterface ni) throws SocketException {
            return !ni.isLoopback() && !ni.isPointToPoint() && ni.isUp() && !ni.isVirtual()
                    && (ni.getName().startsWith("eth") || ni.getName().startsWith("ens"));
        }
    
        /**
         * 判断是否是IPv4,并且内网地址并过滤回环地址.
         */
        private static boolean isValidAddress(InetAddress address) {
            return address instanceof Inet4Address && address.isSiteLocalAddress() && !address.isLoopbackAddress();
        }
    
        /*
         * 通过Socket 唯一确定一个IP
         * 当有多个网卡的时候,使用这种方式一般都可以得到想要的IP。甚至不要求外网地址8.8.8.8是可连通的
         * @return Inet4Address>
         */
        private static Optional getIpBySocket() throws SocketException {
            try (final DatagramSocket socket = new DatagramSocket()) {
                socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
                if (socket.getLocalAddress() instanceof Inet4Address) {
                    return Optional.of((Inet4Address) socket.getLocalAddress());
                }
            } catch (UnknownHostException networkInterfaces) {
                throw new RuntimeException(networkInterfaces);
            }
            return Optional.empty();
        }
    
        /*
         * 获取本地IPv4地址
         * @return Inet4Address>
         */
        public static Optional getLocalIp4Address() throws SocketException {
            final List inet4Addresses = getLocalIp4AddressFromNetworkInterface();
            if (inet4Addresses.size() != 1) {
                final Optional ipBySocketOpt = getIpBySocket();
                if (ipBySocketOpt.isPresent()) {
                    return ipBySocketOpt;
                } else {
                    return inet4Addresses.isEmpty() ? Optional.empty() : Optional.of(inet4Addresses.get(0));
                }
            }
            return Optional.of(inet4Addresses.get(0));
        }
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122

    二、测试结果

    在这里插入图片描述

    请添加图片描述

  • 相关阅读:
    监控web项目都访问了那些网址
    评价聚类的方法
    第8章_聚合函数
    均值滤波算法及例程
    43、基于 springboot 自动配置的 spring mvc 错误处理,就是演示项目报错后,跳转到自定义的错误页面
    程序员实现财务自由的5个方法
    require.context 的使用
    怎样在CSDN赚点零花钱
    Git仓库4(分支操作冲突,标签管理)
    java毕业设计宠物喂养资讯分享平台的设计与实现Mybatis+系统+数据库+调试部署
  • 原文地址:https://blog.csdn.net/weixin_46822367/article/details/132955928