public class IpDetector {
public static String getIp() {
try {
Enumeration<NetworkInterface> em = NetworkInterface.getNetworkInterfaces();
for(;em.hasMoreElements();) {
NetworkInterface ni = em.nextElement();
String nicName = ni.getName();
if (nicName.startsWith("virbr")
|| nicName.startsWith("vboxnet")
|| nicName.startsWith("docker")
) {
continue;
}
Enumeration<InetAddress> emAddr = ni.getInetAddresses();
for(;emAddr.hasMoreElements();) {
InetAddress addr = emAddr.nextElement();
if (addr instanceof Inet4Address) {
String addrStr = addr.getHostAddress();
if (addrStr.startsWith("127.")) {
continue;
}
// System.out.println("Address is "+addr.getHostAddress());
return addrStr;
}
}
System.out.println();
}
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String ip = getIp();
System.out.println("IP is "+ip);
}
}
Java 获取一个机器的本地地址
最新推荐文章于 2022-01-09 23:30:19 发布