首页 > 基础资料 博客日记

Java获取本机IP地址的方法(内网、公网)

2024-07-15 02:00:07基础资料围观203

本篇文章分享Java获取本机IP地址的方法(内网、公网),对你有帮助的话记得收藏一下,看Java资料网收获更多编程知识

起因是公司一个springboot项目启动类打印了本机IP地址加端口号,方便访问项目页面,但是发现打印出来的不是“无线局域网”的ip而是“以太网适配器”ip,如下图所示

这样就导致后续本地起项目连接xxl-job注册节点的时候因为不在同个局域网下ping不通出问题,所以需要解决一下。

一、直接获取本机IP(会受到虚拟机干扰)

public static String getInterIP1() throws Exception {
    return InetAddress.getLocalHost().getHostAddress();
}

二、获取本机IP(排除虚拟机干扰)

public static InetAddress getLocalHostLANAddress() throws UnknownHostException {
        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
                NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                    InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                    if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
                        if (inetAddr.isSiteLocalAddress()) {
                            // 如果是site-local地址,就是它了
                            return inetAddr;
                        } else if (candidateAddress == null) {
                            // site-local类型的地址未被发现,先记录候选地址
                            candidateAddress = inetAddr;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress;
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            if (jdkSuppliedAddress == null) {
                throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
            }
            return jdkSuppliedAddress;
        } catch (Exception e) {
            UnknownHostException unknownHostException = new UnknownHostException(
                    "Failed to determine LAN address: " + e);
            unknownHostException.initCause(e);
            throw unknownHostException;
        }
    }

三、获取本机公网IP

public static String getOutIP() {
    try {
        URL whatismyip = new URL("http://checkip.amazonaws.com");
        BufferedReader in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));

        String ip = in.readLine();
        return ip;

        } catch (Exception e) {}

        return "";
}

四、测试

public class IpTest {

        public static void main(String[] args) throws Exception {
            System.out.println("获取本机ip: " + getInterIP1());
//            System.out.println("getInterIP2: " + getInterIP2());
            System.out.println("获取本机ip(排除虚拟机干扰): " + String.valueOf(getLocalHostLANAddress()).substring(1));
//            System.out.println("getOutIPV4: " + getOutIPV4());
            System.out.println("获取本机公网ip: " + getOutIP());
        }

        public static String getInterIP1() throws Exception {
            return InetAddress.getLocalHost().getHostAddress();
        }

    public static InetAddress getLocalHostLANAddress() throws UnknownHostException {
        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
                NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                    InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                    if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
                        if (inetAddr.isSiteLocalAddress()) {
                            // 如果是site-local地址,就是它了
                            return inetAddr;
                        } else if (candidateAddress == null) {
                            // site-local类型的地址未被发现,先记录候选地址
                            candidateAddress = inetAddr;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress;
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            if (jdkSuppliedAddress == null) {
                throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
            }
            return jdkSuppliedAddress;
        } catch (Exception e) {
            UnknownHostException unknownHostException = new UnknownHostException(
                    "Failed to determine LAN address: " + e);
            unknownHostException.initCause(e);
            throw unknownHostException;
        }
    }
    
        public static String getOutIP() {
            try {
                URL whatismyip = new URL("http://checkip.amazonaws.com");
                BufferedReader in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));

                String ip = in.readLine();
                return ip;
//                System.out.println("Public IP Address: " + ip);
            } catch (Exception e) {
//                System.out.println("Error occurred: " + e.getMessage());
            }
            return "";
        }

}
获取本机ip: 172.17.16.1
获取本机ip(排除虚拟机干扰): 192.168.100.100
获取本机公网ip: 14.145.43.147

这里打印出来的便对应上前言命令行截图里的ip信息,然后公网ip对应的是百度搜索ip查到的公网ip地址 

五、手动禁用虚拟机排除干扰

除了用代码逻辑排除虚拟机干扰,我们也可以直接禁用电脑的虚拟机适配器。

步骤:

  1. win+R 
  2. devmgmt.msc 打开设备管理器
  3. 找到网络适配器-Hyper-V Virtual 开头的  右键禁用

此时win+R cmd 输入ipconfig,可以看到已经没有虚拟机ip了

此时java使用

InetAddress.getLocalHost().getHostAddress()

也可以获取到192.168开头的wifi地址了


文章来源:https://blog.csdn.net/m0_52620144/article/details/139750087
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云