首先,你如果搜索“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;
} }

详谈再论JAVA获取本机IP地址的更多相关文章

  1. java获取本机IP地址

    转载自:http://blog.csdn.net/thunder09/article/details/5360251 在网上找了几个用java获取本机IP地址的代码,发现都少都有些不完美,自己整理了一 ...

  2. java获取本机ip地址(写出来的)

    /** * @author 豪弟 * @param request * @return * @throws IOException */ public final static String getI ...

  3. java获取本机IP地址和MAC地址的方法

    // 获取ip地址 public static String getIpAddress() { try { Enumeration<NetworkInterface> allNetInte ...

  4. java获取本机IP地址,非127.0.0.1

    综合了网上找的代码,整理的,Windows和Linux都可以用. private static String getHostIp(){ try{ Enumeration<NetworkInter ...

  5. java 获取本机ip地址

    /** * 取当前系统站点本地地址 linux下 和 window下可用 * * @return */ public static String getLocalIP() { String sIP = ...

  6. java获取本机ip(排除虚拟机等一些ip)最终解,总算找到方法了

    本文参考https://blog.csdn.net/u011809209/article/details/77236602 本文参考https://blog.csdn.net/yinshuomail/ ...

  7. Java 实例 - 获取本机ip地址及主机名

    package guyu.day0824; import java.net.InetAddress; /** * @Author: Fred * @Date: 2020/8/24 09:39 */ p ...

  8. 关于是用dotnet获取本机IP地址+计算机名的方法

    印象中在maxscript帮助文档里找到过方法,但是当时没记下来.只能通过dotnet实现了. 如果电脑有无线网卡和本地连接,可能会出现乱码,也问了写dotnet的朋友,提供了一些思路,不过最终还是使 ...

  9. Java获取本机MAC地址[转]

    原文地址:https://www.cnblogs.com/hxsyl/p/3422191.html Java获取本机MAC地址   为什么写这个呢?因为前几天看见网上有采用windows命令获取局域网 ...

随机推荐

  1. 微信H5支付 遇到坑的一些解决方法

    解决办法 1. 商家参数格式有误,请联系商家解决 a.对于前后端分离的开发模式 前端发起请求 服务端请求微信h5支付统一下单接口 返回参数mweb_url 给前端 然后前端调起微信h5支付 b.注意的 ...

  2. 20162322 朱娅霖 作业005&006 栈,队列

    20162322 2017-2018-1 <程序设计与数据结构>第五.六周学习总结 教材学习内容总结 集合的介绍(总述) 集合是收集并组织其他对象的对象.主要分为线性集合(集合中的元素排成 ...

  3. oracle 表空间创建和删除

    oracle数据库:数据库对象以及表数据都存储在表空间中,创建用户时可以指定对应的表空间.这样用户可以在各自的表空间中操作数据,互不干扰. 1. 表空间创建 若不清楚表空间对应文件的路径,可以登录系统 ...

  4. [leetcode]205. Isomorphic Strings 同构字符串

    Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the chara ...

  5. [leetcode]54. Spiral Matrix螺旋矩阵

    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral or ...

  6. MongoDB 官网教程 下载 安装

    官网:https://www.mongodb.com/ Doc:https://docs.mongodb.com/ Manual:https://docs.mongodb.com/manual/ 安装 ...

  7. java多线程系列15 设计模式 生产者 - 消费者模式

    生产者-消费者 生产者消费者模式是一个非常经典的多线程模式,比如我们用到的Mq就是其中一种具体实现 在该模式中 通常会有2类线程,消费者线程和生产者线程 生产者提交用户请求 消费者负责处理生产者提交的 ...

  8. Linux 第十天

    十三.权限管理 1.ACL权限开启 1)dumpe2fs -h /dev/sda3查看分区ACL权限是否开启 -h:仅显示超级块中信息,而不显示磁盘块组的详细信息 2)mount -o remount ...

  9. v$lockv和$locked_object的区别

    v$lockv和$locked_object的区别 url: http://blog.sina.com.cn/s/blog_62defbef0101pgvo.html 2013-12-24 v1.0 ...

  10. drf1 rest & restful规范

    web服务交互 我们在浏览器中能看到的每个网站,都是一个web服务.那么我们在提供每个web服务的时候,都需要前后端交互,前后端交互就一定有一些实现方案,我们通常叫web服务交互方案. 目前主流的三种 ...