import lombok.extern.slf4j.Slf4j;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/**
* @author 乐心湖
* @date 2020/7/20 19:36
**/
public class NetUtils {
/**
* 获取本地真正的IP地址,即获得有线或者 无线WiFi 地址。
* 过滤虚拟机、蓝牙等地址
*
* @return IPv4
*/
public static String getRealIP() {
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = allNetInterfaces.nextElement();
// 去除回环接口,子接口,未运行和接口
if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
continue;
}
if (!netInterface.getDisplayName().contains("Intel")
&& !netInterface.getDisplayName().contains("Realtek")
&& !netInterface.getDisplayName().contains("Ethernet")) {
continue;
}
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress ip = addresses.nextElement();
if (ip != null) {
// ipv4
if (ip instanceof Inet4Address) {
return ip.getHostAddress();
}
}
}
break;
}
} catch (SocketException e) {
//捕获异常
}
return null;
}
}
在前辈原有的基础上新增了对 xp 系统的支持
参考资料:https://blog.csdn.net/yinshuomail/article/details/81624648
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有