Java 获取本机 ip 地址 /ipv6 地址,非用户请求返回的 IP
try {String hostAddress = InetAddress.getLocalHost().getHostAddress();
System.out.println("hostAddress:" + hostAddress);
String hostName = InetAddress.getLocalHost().getHostName();
System.out.println("hostName:" + hostName);
if (hostName.length() > 0) {InetAddress[] addrs = InetAddress.getAllByName(hostName);
if (addrs.length > 0) {for (int i = 0; i < addrs.length; i++) {InetAddress address = addrs[i];
System.out.println("**********************");
System.out.println(address.getHostAddress());
if (address instanceof Inet6Address) {System.out.println("true6");
} else if(address instanceof Inet4Address){System.out.println("true4");
} else {System.out.println("unknown");
}
System.out.println("**********************");
}
}
}
} catch (UnknownHostException e) {e.printStackTrace();
}
或者
Enumeration<NetworkInterface> interfs = NetworkInterface.getNetworkInterfaces();
while (interfs.hasMoreElements()) {NetworkInterface interf = interfs.nextElement();
Enumeration<InetAddress> addres = interf.getInetAddresses();
while (addres.hasMoreElements()) {InetAddress in = addres.nextElement();
if (in instanceof Inet4Address) {System.out.println("v4:" + in.getHostAddress());
} else if (in instanceof Inet6Address) {System.out.println("v6:" + in.getHostAddress());
}
}
}