您的位置:首页 > 其它

获取服务所在机器IP地址

2015-10-13 11:29 316 查看
前段时间做定时任务的时候,需要在线上的服务器中的某一台执行定时任务,没有找到更好的方法,就想用IP匹配的方法,执行相应的方法。
获取服务器IP:


public String getLocalIp() {
String ip = "";
try {
// 遍历服务器的网卡地址
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: