Java 获取本地IP地址和主机名

拿到本机 IP不是一件困难的事,但是拿到正确的就比较难了。

一、一般方式

【菜鸟教程】中直接通过 java.net.InetAddress类获取,如下:

import java.net.InetAddress;
 
public class Main {
   public static void main(String[] args) 
   throws Exception {
      InetAddress addr = InetAddress.getLocalHost();
      System.out.println("Local HostAddress: 
      "+addr.getHostAddress());
      String hostname = addr.getHostName();
      System.out.println("Local host name: "+hostname);
   }
}

这种方式获取的主机名没啥问题,但获取到的IP地址却有待考量:如果一台机器有多个网卡,他获取的IP是谁的呢?

事实上,上面输出的IP是我虚拟机IP地址,既不是我有线网卡的地址,也不是我无线网卡的地址。

二、推荐使用

利用 java.net.NetworkInterface 获取,提供常用的静态方法如下:

  1. getLocalHostAddress():返回本机 IP
  2. getLocalHostName():返回主机名
  3. getLocalInetAddress:返回 InetAddress
  4. isWindowsOS():判断操作系统是否是 Windows
  5. isMacOS():判断操作系统是否是 MacOS
public class LocalHostUtil {

    private static InetAddress inetAddress;

    /**
     * 返回 InetAddress
     * @return
     */
    public static InetAddress getLocalInetAddress() {
        if (inetAddress == null) {
            load();
        }
        return inetAddress;
    }

    /**
     * 返回本机IP
     * @return
     */
    public static String getLocalHostAddress() {
        if (inetAddress == null) {
            load();
        }
        return inetAddress.getHostAddress();
    }

    /**
     * 返回主机名
     * @return
     */
    public static String getLocalHostName() {
        if (inetAddress == null) {
            load();
        }
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            return inetAddress.getHostName();
        }
    }

    /**
     * 判断操作系统是否是 Windows
     * @return
     */
    public static boolean isWindowsOS() {
        boolean isWindowsOS = false;
        String osName = getProperty("os.name");
        if (osName.toLowerCase().indexOf("windows") > -1) {
            isWindowsOS = true;
        }
        return isWindowsOS;
    }

    /**
     * 判断操作系统是否是 MacOS
     * @return
     */
    public static boolean isMacOS() {
        boolean isWindowsOS = false;
        String osName = getProperty("os.name");
        if (osName.toLowerCase().indexOf("mac") > -1) {
            isWindowsOS = true;
        }
        return isWindowsOS;
    }

    private static InetAddress findValidateIp(List<Address> addresses) {
        InetAddress local = null;
        int size = addresses.size();
        int maxWeight = -1;

        for (int i = 0; i < size; i++) {
            Address address = addresses.get(i);
            if (address.isInet4Address()) {
                int weight = 0;

                if (address.isSiteLocalAddress()) {
                    weight += 8;
                }

                if (address.isLinkLocalAddress()) {
                    weight += 4;
                }

                if (address.isLoopbackAddress()) {
                    weight += 2;
                }

                if (address.hasHostName()) {
                    weight += 1;
                }

                if (weight > maxWeight) {
                    maxWeight = weight;
                    local = address.getAddress();
                }
            }
        }

        return local;
    }

    private static String getProperty(String name) {
        String value = null;

        value = System.getProperty(name);

        if (value == null) {
            value = System.getenv(name);
        }

        return value;
    }

    private static void load() {
        String ip = getProperty("host.ip");

        if (ip != null) {
            try {
                inetAddress = InetAddress.getByName(ip);
                return;
            } catch (Exception e) {
                System.err.println(e);
                // ignore
            }
        }

        try {
            List<NetworkInterface> nis = Collections.list(NetworkInterface.getNetworkInterfaces());
            List<Address> addresses = new ArrayList<>();
            InetAddress local = null;

            try {
                // 遍历网络接口
                for (NetworkInterface ni : nis) {
                    if (ni.isUp() && !ni.isLoopback()) {
                        List<InetAddress> list = Collections.list(ni.getInetAddresses());
                        // 遍历网络地址
                        for (InetAddress address : list) {
                            addresses.add(new Address(address, ni));
                        }
                    }
                }
                local = findValidateIp(addresses);
            } catch (Exception e) {
                // ignore
            }
            inetAddress = local;
        } catch (SocketException e) {
            // ignore it
        }
    }

    static class Address {
        private InetAddress inetAddress;

        private boolean loopback;

        public Address(InetAddress address, NetworkInterface ni) {
            inetAddress = address;

            try {
                if (ni != null && ni.isLoopback()) {
                    loopback = true;
                }
            } catch (SocketException e) {
                // ignore it
            }
        }

        public InetAddress getAddress() {
            return inetAddress;
        }

        public boolean hasHostName() {
            return !inetAddress.getHostName().equals(inetAddress.getHostAddress());
        }

        public boolean isLinkLocalAddress() {
            return !loopback && inetAddress.isLinkLocalAddress();
        }

        public boolean isLoopbackAddress() {
            return loopback || inetAddress.isLoopbackAddress();
        }

        public boolean isSiteLocalAddress() {
            return !loopback && inetAddress.isSiteLocalAddress();
        }

        public boolean isInet4Address(){
            return inetAddress instanceof Inet4Address;
        }
    }
}

【Github 示例代码】

日常求赞

  1. 祖传秘籍 Spring Boot 葵花宝典 开源中,欢迎前来吐槽,提供线索!
  2. 九阳神功 【Java 知识笔记本】 开源中,欢迎前来吐槽,提供线索!

最新文章,欢迎关注:公众号-风尘博客;交流观点,欢迎添加:个人微信

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值