獲取本地ip地址本來是應該很簡單的,但是在項目中本地實現了之後,放到生產環境卻不行了,一直獲取不到本地ip.
下面先粘出我在生產環境中沒有獲取到ip地址的一般簡單的獲取ip地址的流程,最後面是我的解決方法(代碼):
public static String getLocalIpAddr() {
Enumeration<NetworkInterface> networks = null;
try {
// 獲取網卡設備
networks = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
logger.info(e.getMessage());
}
InetAddress ip = null;
Enumeration<InetAddress> addrs;
// 遍歷網卡設備
while (networks.hasMoreElements()){
addrs = networks.nextElement().getInetAddresses();
while (addrs.hasMoreElements()){
ip = addrs.nextElement();
if (ip != null && ip instanceof InetAddress && ip.isSiteLocalAddress()){
if (ip.getHostAddress()==null || "".equals(ip.getHostAddress())){
logger.info("獲取到的客戶端內網ip爲空,從配置文件讀取本地ip。");
return null;
}
return ip.getHostAddress();// 客戶端ip
}
}
}
return null;
}
這樣獲取在生產環境中出現了ip地址獲取不到的情況,因此修改成下面的非常規方法來獲取了(皮一下,哈哈):
public static String getLocalIpAddr() {
String clientIP = null;
Enumeration<NetworkInterface> networks = null;
try {
//獲取所有網卡設備
networks = NetworkInterface.getNetworkInterfaces();
if (networks == null) {
//沒有網卡設備 打印日誌 返回null結束
logger.info("networks is null");
return null;
}
} catch (SocketException e) {
System.out.println(e.getMessage());
}
InetAddress ip;
Enumeration<InetAddress> addrs;
// 遍歷網卡設備
while (networks.hasMoreElements()) {
NetworkInterface ni = networks.nextElement();
try {
//過濾掉 loopback設備、虛擬網卡
if (!ni.isUp() || ni.isLoopback() || ni.isVirtual()) {
continue;
}
} catch (SocketException e) {
logger.info(e.getMessage());
}
addrs = ni.getInetAddresses();
if (addrs == null) {
logger.info("InetAddress is null");
continue;
}
// 遍歷InetAddress信息
while (addrs.hasMoreElements()) {
ip = addrs.nextElement();
if (!ip.isLoopbackAddress() && ip.isSiteLocalAddress() && ip.getHostAddress().indexOf(":") == -1) {
try {
clientIP = ip.toString().split("/")[1];
} catch (ArrayIndexOutOfBoundsException e) {
clientIP = null;
}
}
}
}
return clientIP;
}
因爲打印InetAddress對象的時候會打印成 /xxx.xxx.xxx.xxx 這樣的格式,所以直接就將這個字符串解析了,雖然比較粗暴,但是也是有效的。