Skip to content

Instantly share code, notes, and snippets.

@geekyouth
Created August 31, 2019 11:35
Show Gist options
  • Save geekyouth/b2dc162dfb06e53fed30dafa6b8b6b76 to your computer and use it in GitHub Desktop.
Save geekyouth/b2dc162dfb06e53fed30dafa6b8b6b76 to your computer and use it in GitHub Desktop.
package cn.java666.jobtracker.common;
import org.junit.Test;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/**
* @author Geek
* @date 2019-08-31 19:17:53
*
* 获取本地真正的IP地址,即获得有线或者无线WiFi地址。
* 过滤虚拟机、蓝牙等地址
*/
public class GetRealLocalIP {
@Test
public void test1() {
getRealIP();
}
/**
* 获取本地真正的IP地址,即获得有线或者无线WiFi地址。
* 过滤虚拟机、蓝牙等地址
*/
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")) {
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment