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地址 

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

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

步骤:

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

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

此时java使用

InetAddress.getLocalHost().getHostAddress()

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

要在微信公众号H5开发使用Vue横屏签名,可以遵循以下步骤: 1.Vue项目中安装`vue-orientjs`插件,该插件可以帮助我们在Vue项目中使用横屏签名功能。 2.Vue项目的入口文件中引入`vue-orientjs`插件,并在Vue实例中注册该插件。 ```javascript import Vue from &#39;vue&#39; import VueOrientjs from &#39;vue-orientjs&#39; // 注册插件 Vue.use(VueOrientjs) ``` 3. 在需要使用横屏签名的组件中,使用`v-orient`指令来绑定横屏签名功能。 ```html <template> <div v-orient> // 横屏签名区域 </div> </template> ``` 4. 在横屏签名区域中,使用canvas元素来绘制签名。 ```html <template> <div v-orient> <canvas ref="canvas"></canvas> </div> </template> ``` 5.Vue组件的`mounted`钩子函数中,获取canvas元素的实例,并进行签名相关的初始化操作。 ```javascript mounted() { const canvas = this.$refs.canvas const ctx = canvas.getContext(&#39;2d&#39;) // 签名相关的初始化操作 } ``` 6. 在横屏签名区域中,添加相应的事件监听器来响应用户的签名操作。 ```javascript methods: { handleStart(event) { // 签名开始操作 }, handleMove(event) { // 签名移动操作 }, handleEnd(event) { // 签名结束操作 } } ``` 通过以上步骤,我们就可以在Vue项目中实现横屏签名的功能了。需要注意的是,在微信公众号H5开发中,由于微信浏览器的限制,需要用户在签名前先将手机横屏显示。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值