Java 获取服务器ip地址
import ;
import ;
import ;
public class WebToolUtils {
/**
* 获取本地IP地址
*
* @throws Exception
*/
public static String getLocalIP() throws Exception {
if (isWindowsOS()) {
return ().getHostAddress();
} else {
return getLinuxLocalIp();
}
}
/**
* 获取Linux下的IP地址
*
* @return IP地址
* @throws Exception
*/
private static String getLinuxLocalIp() throws Exception {
String ip = "";
try {
for (Enumeration<NetworkInterface> en = (); (); ) {
NetworkInterface intf = ();
String name = ();
if (!("docker") && !("lo")) {
for (Enumeration<InetAddress> enumIpAddr = (); (); ) {
InetAddress inetAddress = ();
if (!()) {
String ipaddress = ().toString();
if (!("::") && !("0:0:") && !("fe80")) {
ip = ipaddress;
(ipaddress);
}
}
}
}
}
} catch (Exception ex) {
();
}
return ip;
}
/**
* 判断操作系统是否是Windows
*
* @return
*/
public static boolean isWindowsOS() {
boolean isWindowsOS = false;
String osName = ("");
if (().indexOf("windows") > -1) {
isWindowsOS = true;
}
return isWindowsOS;
}
public static void main(String[] args) throws Exception {
(getLocalIP());
}
}