前段時間做定時任務的時候,需要在線上的服務器中的某一臺執行定時任務,沒有找到更好的方法,就想用IP匹配的方法,執行相應的方法。
獲取服務器IP:
public String getLocalIp() {
String ip = ""
try {
// 遍歷服務器的網卡地址
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces()
NetworkInterface intf = en.nextElement()
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses()
InetAddress inetAddress = enumIpAddr.nextElement()
if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
ip = inetAddress.getHostAddress().toString()
}
}
}
} catch (SocketException ex) {
logger.error("getLocalIp 獲取服務器IP異常:" + ex)
}
logger.info("getLocalIp 獲取服務器IP = :" + ip)
return ip
}