项目中遇到了要获取本地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)的更多相关文章

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

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

  2. JAVA获取本机的MAC地址

    /** * 获取本机的Mac地址 * @return */ public String getMac() { InetAddress ia; byte[] mac = null; try { // 获 ...

  3. Delphi获取本机的MAC地址

    Delphi获取本机的MAC地址: uses   NB30; function GetAdaPterInfo(lana: Char): string; var   Adapter: TAdapterS ...

  4. PHP获取IP地址的方法,防止伪造IP地址注入攻击

    PHP获取IP地址的方法 /** * 获取客户端IP地址 * <br />来源:ThinkPHP * <br />"X-FORWARDED-FOR" 是代理 ...

  5. IP地址及子网--四种IP广播地址

    国际规定:把所有的IP地址划分为 A,B,C,D,E. 类默认子网掩码:A类为 255.0.0.0; B类为 255.255.0.0; C类为 255.255.255.0.子网掩码是一个32位地址,用 ...

  6. 没有IP地址的主机怎样保持IP层联通

    在<两台不同网段的PC直连能否够相互ping通>一文中,我有点像在玩旁门左道,本文中.我继续走火入魔.两台机器,M1和M2,各自有一个网卡eth0,配置例如以下:M1的配置:eth0上不配 ...

  7. 推断给定的IP地址是否是内网IP

    /** * 推断给定的IP地址是否是内网IP * * @author GaoHuanJie */ public class Test{ public boolean isInnerIP(String ...

  8. Nginx禁止直接通过IP地址访问网站以及限制IP登陆某目录(关闭默认站点或空主机头)

    这篇文章主要介绍了Nginx中禁止使用IP访问网站的配置实例,一般在备案时可能需要这种设置,需要的朋友可以参考下   国内因为备案的原因,所有服务器都要禁止使用IP访问网站.否则,如果允许使用IP访问 ...

  9. 第14.17节 爬虫实战3: request+BeautifulSoup实现自动获取本机上网公网地址

    一. 引言 一般情况下,没有特殊要求的客户,宽带服务提供商提供的上网服务,给客户家庭宽带分配的地址都是一个宽带服务提供商的内部服务地址,真正对外访问时通过NAT进行映射到一个公网地址,如果我们想确认自 ...

  10. Centos7安装完毕后联网-设置ip地址(VMware虚拟机)

    VMware虚拟机中安装了Centos7,为了让Centos能够访问外网及设置固定的ip地址以方便本地通过SSH访问Centos,做以下几步.本文来自osfipin note. 1.确认虚拟机网络链接 ...

随机推荐

  1. Flask系列10-- Flask请求上下文源码分析

    总览 一.基础准备. 1. local类 对于一个类,实例化得到它的对象后,如果开启多个线程对它的属性进行操作,会发现数据时不安全的 import time from threading import ...

  2. 【文文殿下】P3737 [HAOI2014]遥感监测

    题解 显然可以把每个观测点,认为是x轴上的一段区间.问题就转换为了:对于x轴上的若干个区间,选取尽可能少的点,使得所有区间都有至少一个点. 这是一个相当经典的贪心问题. 代码如下: #include& ...

  3. Spring MVC前后端数据交互总结

    控制器 作为控制器,大体的作用是作为V端的数据接收并且交给M层去处理,然后负责管理V的跳转.SpringMVC的作用不外乎就是如此,主要分为:接收表单或者请求的值,定义过滤器,跳转页面:其实就是ser ...

  4. python2 里边自定义线程池

    #!/usr/bin/env python # -*- coding:utf-8 -*- import Queue import threading class ThreadPool(object): ...

  5. Hadoop 2.4.1+HBase 0.98.6.1 分布式安装

    参考:http://blog.csdn.net/wind520/article/details/39856353

  6. Your Mac is infected with (3) Viruses!

    记一次流氓程序的清理 某天我的电脑不幸感染了这么一个病毒

  7. jquery控制input只能输入数字和两位小数

    jquery代码 function num(obj){ obj.value = obj.value.replace(/[^\d.]/g,""); //清除"数字" ...

  8. java学习--高效的除模取余运算(n-1)&hash

    没有测试过使用取余运算符和位运算符都做同一件事时的时间效率! 取余运算符% 如3除以2取余数 a = a%; 结果为1 上面是传统的方式进行求余运算. 需要先将10进制转成2进制到内存中进行计算,然后 ...

  9. MVC源码分析 - View

    感觉好久没有学习了, 汗. 年就这么过完了, 感觉没有尝到过年的味道. 现在的年过的有些冷清了. 除了体重证明着我过了一个年, 还有一件值得开心的事情, 终于把女朋友变成未婚妻了. 这是一大进步吧. ...

  10. Tomcat学习总结(8)——Tomcat+Nginx集群解决均衡负载及生产环境热部署

    近日,为解决生产环境热部署问题,决定在服务器中增加一个tomcat组成集群,利用集群解决热部署问题. 这样既能解决高并发瓶颈问题,又能解决热部署(不影响用户使用的情况下平滑更新生产服务器)问题. 因为 ...