获取本机各种IP地址,所有IP地址,局域网IP地址,IPV4/IPV6 IP地址

1.获取局域网IP地址

String hostAddress = InetAddress.getLocalHost().getHostAddress();
System.out.println("获取局域网IP地址:" + hostAddress);

2.获取全部 IPV4/IPV6 IP地址

    /**
     * 获取全部 IPV4/IPV6 IP地址:
     *
     * @return
     * @throws SocketException
     */
    private static List<String> getIpAddress() throws SocketException {
    
    
        List<String> list = new LinkedList<>();
        Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
        while (enumeration.hasMoreElements()) {
    
    
            NetworkInterface network = enumeration.nextElement();
            if (!(network.isVirtual() || !network.isUp())) {
    
    
                Enumeration<InetAddress> addresses = network.getInetAddresses();
                while (addresses.hasMoreElements()) {
    
    
                    InetAddress address = addresses.nextElement();
                    if ((address instanceof Inet4Address || address instanceof Inet6Address)) {
    
    
                        list.add(address.getHostAddress());
                    }
                }
            }
        }
        return list;
    }

3.获取全部存放本机IP地址

    /**
     * 获取全部存放本机IP地址
     *
     * @return
     * @throws SocketException
     */
    private static List<String> getAllIpAddress() throws SocketException {
    
    
        List<String> list = new LinkedList<>();
        Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
        while (enumeration.hasMoreElements()) {
    
    
            NetworkInterface network = enumeration.nextElement();
            Enumeration<InetAddress> addresses = network.getInetAddresses();
            while (addresses.hasMoreElements()) {
    
    
                InetAddress address = addresses.nextElement();
                if ((address instanceof Inet4Address || address instanceof Inet6Address)) {
    
    
                    list.add(address.getHostAddress());
                }
            }
        }
        return list;
    }

猜你喜欢

转载自blog.csdn.net/weixin_45265547/article/details/127792890