![java获取本机IP地址,非127.0.0.1 java获取本机IP地址,非127.0.0.1](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
综合了网上找的代码,整理的,Windows和Linux都可以用。
-
private static String getHostIp(){
-
try{
-
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
-
while (allNetInterfaces.hasMoreElements()){
-
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
-
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
-
while (addresses.hasMoreElements()){
-
InetAddress ip = (InetAddress) addresses.nextElement();
-
if (ip != null
-
&& ip instanceof Inet4Address
-
&& !ip.isLoopbackAddress() //loopback地址即本机地址,IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
-
&& ip.getHostAddress().indexOf(":")==-1){
-
System.out.println("本机的IP = " + ip.getHostAddress());
-
return ip.getHostAddress();
-
}
-
}
-
}
-
}catch(Exception e){
-
e.printStackTrace();
-
}
-
return null;
-
}