获取服务所在机器IP地址

来源:互联网 发布:华为手机 知乎 编辑:程序博客网 时间:2024/06/06 14:11
前段时间做定时任务的时候,需要在线上的服务器中的某一台执行定时任务,没有找到更好的方法,就想用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;    }
1 0
原创粉丝点击