Java获取当前服务器信息
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
/**
* @Description 获取本机信息
* @ClassName LocalInfoUtil
* @Author guo
* @Date 2021/12/13 20:21
* @Version 1.0
*/
public class LocalInfoUtil {
public static String getIpAddress() {
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
continue;
} else {
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
return ip.getHostAddress();
}
}
}
}
} catch (Exception e) {
System.err.println("IP地址获取失败" + e.toString());
}
return "";
}
public static String getHostName(){
try {
InetAddress addr = InetAddress.getLocalHost();
return addr.getHostName();
} catch (Exception e){
System.err.println("本机名称获取失败" + e.toString());
}
return "";
}
public static void main(String args[]){
System.out.println("本机IP地址 : " + getIpAddress());
System.out.println("本机名称 : " + getHostName());
}
}