获取本机的ip地址(排除虚拟机,蓝牙等ip)
项目中遇到了要获取本地ip的需求,网上查找资料遇到很多坑,很多Java获取本机ip地址的方法要么是根本获取不到,要么是获取的有问题。
网上常见的方法如下
InetAddress.getLocalHost().getHostAddress()
但是如果电脑里面有Lan,WIFI,蓝牙热点,虚拟机网卡,即存在很多的网络接口(network interfaces),每个网络接口就包含一个IP地址,并不是所有的IP地址能被外部或局域网访问,比如说虚拟机网卡地址等等。上面获取到的ip就会有误。
下面是正确的获取ip地址的方法,亲测无误:
方法一:
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
public class getRealIp {
public static void main(String[] args) {
try {
// 正确的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;
}
}
}
参考博客地址:https://blog.csdn.net/u011809209/article/details/77236602
这里插上一句,上面的方法之前在java项目中能准确获取到ip,但是放在项目中之后,又不能获取准确的ip,也是很迷,然后又另外找了一种方法,如下:
方法二:
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/**
* 获取本地真正的IP地址,即获得有线或者无线WiFi地址。
* 过滤虚拟机、蓝牙等地址
*/
public class getRealLocalIP {
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;
}
}
参考博客地址:https://blog.csdn.net/yinshuomail/article/details/81624648
总之网上比较靠谱的方法就找到这两种,感谢其他博主的博客。
获取本机的ip地址(排除虚拟机,蓝牙等ip)的更多相关文章
- java获取本机ip(排除虚拟机等一些ip)最终解,总算找到方法了
本文参考https://blog.csdn.net/u011809209/article/details/77236602 本文参考https://blog.csdn.net/yinshuomail/ ...
- JAVA获取本机的MAC地址
/** * 获取本机的Mac地址 * @return */ public String getMac() { InetAddress ia; byte[] mac = null; try { // 获 ...
- Delphi获取本机的MAC地址
Delphi获取本机的MAC地址: uses NB30; function GetAdaPterInfo(lana: Char): string; var Adapter: TAdapterS ...
- PHP获取IP地址的方法,防止伪造IP地址注入攻击
PHP获取IP地址的方法 /** * 获取客户端IP地址 * <br />来源:ThinkPHP * <br />"X-FORWARDED-FOR" 是代理 ...
- IP地址及子网--四种IP广播地址
国际规定:把所有的IP地址划分为 A,B,C,D,E. 类默认子网掩码:A类为 255.0.0.0; B类为 255.255.0.0; C类为 255.255.255.0.子网掩码是一个32位地址,用 ...
- 没有IP地址的主机怎样保持IP层联通
在<两台不同网段的PC直连能否够相互ping通>一文中,我有点像在玩旁门左道,本文中.我继续走火入魔.两台机器,M1和M2,各自有一个网卡eth0,配置例如以下:M1的配置:eth0上不配 ...
- 推断给定的IP地址是否是内网IP
/** * 推断给定的IP地址是否是内网IP * * @author GaoHuanJie */ public class Test{ public boolean isInnerIP(String ...
- Nginx禁止直接通过IP地址访问网站以及限制IP登陆某目录(关闭默认站点或空主机头)
这篇文章主要介绍了Nginx中禁止使用IP访问网站的配置实例,一般在备案时可能需要这种设置,需要的朋友可以参考下 国内因为备案的原因,所有服务器都要禁止使用IP访问网站.否则,如果允许使用IP访问 ...
- 第14.17节 爬虫实战3: request+BeautifulSoup实现自动获取本机上网公网地址
一. 引言 一般情况下,没有特殊要求的客户,宽带服务提供商提供的上网服务,给客户家庭宽带分配的地址都是一个宽带服务提供商的内部服务地址,真正对外访问时通过NAT进行映射到一个公网地址,如果我们想确认自 ...
- Centos7安装完毕后联网-设置ip地址(VMware虚拟机)
VMware虚拟机中安装了Centos7,为了让Centos能够访问外网及设置固定的ip地址以方便本地通过SSH访问Centos,做以下几步.本文来自osfipin note. 1.确认虚拟机网络链接 ...
随机推荐
- [JavaScript] Nginx实现跨域设置
假如跨域请求的接口为:http://xxx.cn/was5/web/search Nginx配置: 在conf/nginx.conf文件中 location / { root html; index ...
- Spring boot mybatis : Error creating bean with name 'com.github.pagehelper.autoconfigure.MapperAutoConfiguration': Invocation of init method failed;
报错截图: 解决方法: 只能扫描到自定义的mapper,不能扫描到其他文件. @MapperScan("com.streamax.s17.tms.dao.pper.repository&qu ...
- Apache JMeter的基本使用
安装 安装地址:http://jmeter.apache.org/download_jmeter.cgi 解压后运行jmeter.bat的批处理文件就可以了 JMeter测试脚本编写: 1,创建线程组 ...
- sql开启远程访问
我们用的是SQL Server 数据库 2008 版本,数据库配置完之后从另一台电脑访问数据库死活连接不上,提示信息如下 “ 无法连接到 *.*.*.*. 在于SQL Server建立连接时出现与网络 ...
- Docker 镜像安装 GitLab 中文社区版
docker run \ --detach \ --publish : \ --publish : \ --name gitlab \ --restart unless-stopped \ --vol ...
- Hadoop和Apache Spark的异同
谈到大数据,相信大家对Hadoop和Apache Spark这两个名字并不陌生.但我们往往对它们的理解只是提留在字面上,并没有对它们进行深入的思考,下面不妨跟我一块看下它们究竟有什么异同. 1.解决问 ...
- ssh-key的复制
执行ssh-keygen 生产钥 在b主机root目录创建.ssh文件夹 在a主机输入ssh-copy-id root@*.*.*.* 就把公钥复制过去了 命令:scp 不同的Linux之间copy文 ...
- css定位“十字架“之水平垂直居中
1.先看要实现的效果 实际的效果图 可以看到我的实现过程是先使用一个父级的div来定位水平垂直居中,然后再父级的div中定位出两个十字架的div. 看实现代码: <!DOCTYPE HTML P ...
- Android_EditText 密码框默认是小圆点 怎么改成其它的(*)?
text.setTransformationMethod(new AsteriskPasswordTransformationMethod()); public class AsteriskPassw ...
- 全网最详细的Windows系统里PLSQL Developer 64bit的下载与安装过程(图文详解)
不多说,直接上干货! ORACLE是数据库,有客户端和服务器: 其,具体下载,可见http://www.oracle.com/technetwork/database/enterprise-editi ...