java获取本机ip(排除虚拟机等一些ip)最终解,总算找到方法了
本文参考https://blog.csdn.net/u011809209/article/details/77236602
本文参考https://blog.csdn.net/yinshuomail/article/details/81624648
首先,你如果搜索“JAVA获取本机IP地址”,基本上搜到的资料全是无用的。
实际上的代码在复杂环境下是不准的
网上一个比较普遍的说法是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地址的正确姿势:
public class Test{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 void main(String[] args){
//打印本机本地地址
System.out.println(SocketServer.getLocalHostLANAddress().toString().substring(1));
}
}
/**
* @author yins
* @date 2018年8月12日下午9:53:58
*/
package org.pdkj.web.commons.ip;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/**
* 获取本地真正的IP地址,即获得有线或者无线WiFi地址。
* 过滤虚拟机、蓝牙等地址
* @author yins
* @date 2018年8月12日 下午9:53:58
*/
public class GetRealLocalIP {
/**
* 获取本地真正的IP地址,即获得有线或者无线WiFi地址。
* 过滤虚拟机、蓝牙等地址
* @author yins
* @date 2018年8月12日下午9:56:35
* @return
*/
public static String getRealIP() {
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface
.getNetworkInterfaces();
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces
.nextElement();
// 去除回环接口,子接口,未运行和接口
if (netInterface.isLoopback() || netInterface.isVirtual()
|| !netInterface.isUp()) {
continue;
}
if (!netInterface.getDisplayName().contains("Intel")
&& !netInterface.getDisplayName().contains("Realtek")) {
continue;
}
Enumeration<InetAddress> addresses = netInterface
.getInetAddresses();
System.out.println(netInterface.getDisplayName());
while (addresses.hasMoreElements()) {
InetAddress ip = addresses.nextElement();
if (ip != null) {
// ipv4
if (ip instanceof Inet4Address) {
System.out.println("ipv4 = " + ip.getHostAddress());
return ip.getHostAddress();
}
}
}
break;
}
} catch (SocketException e) {
System.err.println("Error when getting host ip address"
+ e.getMessage());
}
return null;
}
}
此代码中只要读取到了WiFi或者有线地址其中之一立即return。
java获取本机ip(排除虚拟机等一些ip)最终解,总算找到方法了的更多相关文章
- 详谈再论JAVA获取本机IP地址
首先,你如果搜索“JAVA获取本机IP地址”,基本上搜到的资料全是无用的.比如这篇:http://www.cnblogs.com/zrui-xyu/p/5039551.html实际上的代码在复杂环境下 ...
- java获取本机IP地址
转载自:http://blog.csdn.net/thunder09/article/details/5360251 在网上找了几个用java获取本机IP地址的代码,发现都少都有些不完美,自己整理了一 ...
- java获取本机名称、IP、MAC地址和网卡名称
java获取本机名称.IP.MAC地址和网卡名称 摘自:https://blog.csdn.net/Dai_Haijiao/article/details/80364370 2018年05月18日 1 ...
- Java获取本机MAC地址[转]
原文地址:https://www.cnblogs.com/hxsyl/p/3422191.html Java获取本机MAC地址 为什么写这个呢?因为前几天看见网上有采用windows命令获取局域网 ...
- c#中如何获取本机用户名、MAC地址、IP地址、硬盘ID、CPU序列号、系统名称、物理内存
我们在利用C#开发桌面程序(Winform)程序的时候, 经常需要获取一些跟系统相关的信息, 以下这些代码获取能有些用处. c#中如何获取本机用户名.MAC地址.IP地址.硬盘ID.CPU序列号.系统 ...
- java获取本机机器名
java获取本机机器名 InetAddress.getLocalHost().getHostName().toString();
- JAVA获取本机IP和Mac地址
在项目中,时常需要获取本机的Ip或是Mac地址,进行身份和权限验证,本文就是通过java代码获取ip和Mac. package com.svse.query;import java.net.In ...
- Java获取本机IP
try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); whil ...
- Java 获取本机局域网内IP
主要涉及NetworkInterface.Enumeration.InetAddress等类 /* 获取本机网内地址 */ public static InetAddress getInet4Addr ...
随机推荐
- docker swarm:Error response from daemon: rpc error: code = Unavailable desc = grpc: the connection is unavailable
环境:cetos7 描述:创建完docker swarm,想把node主机加入swarm中,执行以下命令时,报错 无法连接! 原因是:防火墙!!!!!!!没关!!!! 解决办法是:关闭防火墙
- 使用readAsDataURL方法预览图片
使用FileReader接口的readAsDataURL方法实现图片的预览. 在FileReader出现之前,前端的图片预览是这样实现的:把本地图片上传到服务器,服务器把图片地址返回,并把它替换到图片 ...
- UVA1609-Foul Play(构造+递归)
Problem UVA1609-Foul Play Accept: 101 Submit: 514Time Limit: 3000 mSec Problem Description Input Fo ...
- 获得数值型数组的所有元素之和(分别使用增强for循环和普通for循环)
package com.Summer_0419.cn; /** * @author Summer * 获得数值型数组的所有元素之和 */public class Test_Method13 { pub ...
- CRF 条件随机场工具包
CRF - 条件随机场 工具包(python/c++) 项目案例 ConvCRF+FullCRF https://github.com/MarvinTeichmann/ConvCRF 需要的包Opti ...
- ODOO(ERP源码安装)
cat /etc/centos-release CentOS Linux release 7.4.1708 (Core) uname -r 3.10.0-693.el7.x86_64 IP:192.1 ...
- 面试笔记--Fast-Fail(快速失败)机制
1.解决: fail-fast机制,是一种错误检测机制.它只能被用来检测错误,因为JDK并不保证fail-fast机制一定会发生.若在多线程环境下使用fail-fast机制的集合,建议使用“java. ...
- BZOJ3489 A simple rmq problem K-D Tree
传送门 什么可持久化树套树才不会写呢,K-D Tree大法吼啊 对于第\(i\)个数,设其前面最后的与它值相同的位置为\(pre_i\),其后面最前的与它值相同的位置为\(aft_i\),那么对于一个 ...
- 开源后的.Net 如何选择使用
.NET是跨平台的开发栈.它有一个标准库,称为.NET Standard Library,其中包含了大量的APIs.这个标准库由各种.NET运行环境实现:.NET Framework..NET Co ...
- SQLServer 存储过程+定时任务发邮件
SQLServer 代理发邮件需要开启SQL Server 代理服务器,然后,在[管理]-[数据库邮件]中,右键点击配置数据库邮件. 我用的是腾讯的企业邮箱,个人的163邮箱略微不同.下图是相关邮件的 ...