引入的包:
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
方法1:
private static String getHostIP() throws SocketException {
String ip = "";
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
String name = intf.getName();
if (!name.contains("docker") && !name.contains("lo")) {
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ipaddress = inetAddress.getHostAddress().toString();
if (!ipaddress.contains("::") && !ipaddress.contains("0:0:")
&& !ipaddress.contains("fe80")) {
ip = ipaddress;
}
}
}
}
}
} catch (SocketException ex) {
ip = "127.0.0.1";
ex.printStackTrace();
}
return ip;
}
方法2:
private String getHostIP(){
String tempIP = "127.0.0.1";
try {
tempIP = InetAddress.getLocalHost().getHostAddress();
} catch (Exception e) {
logger.error("PptFileUploadController-getHostIP221 获取机器ip失败, ", e);
}
System.out.println(tempIP);
try{
Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
Enumeration<InetAddress> addrs;
while (networks.hasMoreElements()) {
addrs = networks.nextElement().getInetAddresses();
while (addrs.hasMoreElements()) {
ip = addrs.nextElement();
if (ip != null
&& ip instanceof Inet4Address
&& ip.isSiteLocalAddress()
&& !ip.getHostAddress().equals(tempIP)) {
return ip.getHostAddress();
}
}
}
} catch(Exception e){
logger.error("PptFileUploadController-getHostIP223 获取机器ip失败, ", e);
}
return tempIP;
}
方法3:
private String getHostIP(){
Enumeration<NetworkInterface> allNetInterfaces = null;
String resultIP=null;
try {
allNetInterfaces = NetworkInterface.getNetworkInterfaces();
} catch (Exception e) {
logger.error("PptFileUploadController-getHostIP 获取机器ip失败, ", e);
}
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = (InetAddress) addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
if (resultIP==null) {
resultIP= ip.getHostAddress();
}
System.out.println("本机地址是:"+ip.getHostAddress());
}
}
}
return resultIP;
}