当前位置: 首页 > news >正文

详谈再论JAVA获取本机IP地址

首先,你如果搜索“JAVA获取本机IP地址”,基本上搜到的资料全是无用的。
比如这篇:http://www.cnblogs.com/zrui-xyu/p/5039551.html
实际上的代码在复杂环境下是不准的


网上一个比较普遍的说法是InetAddress.getLocalHost().getHostAddress()
似乎很简单,但忽略了一个问题,即IP地址在现在的网络环境更加复杂了,比如有Lan,WIFI,蓝牙热点,虚拟机网卡...
即存在很多的网络接口(network interfaces),每个网络接口就包含一个IP地址,并不是所有的IP地址能被外部或局域网访问,比如说虚拟机网卡地址等等。
也就是说InetAddress.getLocalHost().getHostAddress()的IP不一定是正确的IP。

写代码前,先明确一些规则:

  • 127.xxx.xxx.xxx 属于"loopback" 地址,即只能你自己的本机可见,就是本机地址,比较常见的有127.0.0.1;
  • 192.168.xxx.xxx 属于private 私有地址(site local address),属于本地组织内部访问,只能在本地局域网可见。同样10.xxx.xxx.xxx、从172.16.xxx.xxx 到 172.31.xxx.xxx都是私有地址,也是属于组织内部访问;
  • 169.254.xxx.xxx 属于连接本地地址(link local IP),在单独网段可用
  • 从224.xxx.xxx.xxx 到 239.xxx.xxx.xxx 属于组播地址
  • 比较特殊的255.255.255.255 属于广播地址
  • 除此之外的地址就是点对点的可用的公开IPv4地址

 

获取本机IP地址的正确姿势:

package ipTest;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class Test {

    public Test() {
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        InetAddress ip;
        try {
            // 这种IP容易拿错
            // System.out.println("Current IP address : " +
            // InetAddress.getLocalHost().getHostAddress());
            // 不一定准确的IP拿法
            // 出自比如这篇:http://www.cnblogs.com/zrui-xyu/p/5039551.html
            System.out.println("get LocalHost Address : " + getLocalHostAddress().getHostAddress());

            // 正确的IP拿法
            System.out.println("get LocalHost LAN Address : " + getLocalHostLANAddress().getHostAddress());


        } catch (UnknownHostException e) {

            e.printStackTrace();

        }
    }

    // 正确的IP拿法,即优先拿site-local地址
    private 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;
        }
    }

    //出自这篇:http://www.cnblogs.com/zrui-xyu/p/5039551.html
    //实际上的代码是不准的
    private static InetAddress getLocalHostAddress() throws UnknownHostException {
        Enumeration allNetInterfaces;
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();

                Enumeration addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = (InetAddress) addresses.nextElement();
                    if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
                        if (ip != null && ip instanceof Inet4Address) {
                            return ip;
                        }
                    }
                }
            }
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
        if (jdkSuppliedAddress == null) {
            throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
        }
        return jdkSuppliedAddress;
    }

}

 

相关文章:

  • Unity里包裹Debug,且不影响Debug的重定向
  • AtCoder Regular Contest 075 D Widespread
  • 简易相应式布局。
  • 一个简单有趣的微信聊天机器人
  • windows上安装redis
  • Date类型
  • C#读写配置文件Config
  • js 简单实现隐藏和显示
  • 微软ASP.NET网站部署指南(9):部署数据库更新
  • 使用openssl配置tomcat
  • iframe在ie和firefox中的高度兼容性问题解决
  • spring boot集成mybatis
  • Bootstrap栅格系统
  • 双主模型高可用负载均衡集群的实现(keepalived+lvs-dr)
  • Google Play商店400款App藏恶意代码:手机可变监听站
  • 《用数据讲故事》作者Cole N. Knaflic:消除一切无效的图表
  • 【Redis学习笔记】2018-06-28 redis命令源码学习1
  • 2018以太坊智能合约编程语言solidity的最佳IDEs
  • 4月23日世界读书日 网络营销论坛推荐《正在爆发的营销革命》
  • angular组件开发
  • CSS3 变换
  • in typeof instanceof ===这些运算符有什么作用
  • iOS | NSProxy
  • iOS动画编程-View动画[ 1 ] 基础View动画
  • laravel with 查询列表限制条数
  • mysql innodb 索引使用指南
  • python学习笔记 - ThreadLocal
  • Redux 中间件分析
  • SpringBoot几种定时任务的实现方式
  • sublime配置文件
  • 构建二叉树进行数值数组的去重及优化
  • 排序算法之--选择排序
  • 配置 PM2 实现代码自动发布
  • 七牛云 DV OV EV SSL 证书上线,限时折扣低至 6.75 折!
  • 前端js -- this指向总结。
  • 手写一个CommonJS打包工具(一)
  • 树莓派用上kodexplorer也能玩成私有网盘
  • #预处理和函数的对比以及条件编译
  • $ is not function   和JQUERY 命名 冲突的解说 Jquer问题 (
  • (01)ORB-SLAM2源码无死角解析-(56) 闭环线程→计算Sim3:理论推导(1)求解s,t
  • (10)Linux冯诺依曼结构操作系统的再次理解
  • (cos^2 X)的定积分,求积分 ∫sin^2(x) dx
  • (C语言)fread与fwrite详解
  • (iPhone/iPad开发)在UIWebView中自定义菜单栏
  • (利用IDEA+Maven)定制属于自己的jar包
  • (转)http-server应用
  • *1 计算机基础和操作系统基础及几大协议
  • .Net - 类的介绍
  • .net 7 上传文件踩坑
  • .NET HttpWebRequest、WebClient、HttpClient
  • .net连接MySQL的方法
  • .net连接oracle数据库
  • .NET上SQLite的连接
  • .NET性能优化(文摘)
  • :如何用SQL脚本保存存储过程返回的结果集