java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java获取本机IP地址

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

作者:EIL_XU_

在IT领域获取本机IP地址是一项基础但重要的任务,特别是在网络编程、远程协作和设备通信中,这篇文章主要给大家介绍了关于Java获取本机IP地址的方法(内网、公网),需要的朋友可以参考下

起因是公司一个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地址 

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

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

步骤:

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

此时java使用

InetAddress.getLocalHost().getHostAddress()

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

总结

到此这篇关于Java获取本机IP地址的文章就介绍到这了,更多相关Java获取本机IP地址内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文