獲取服務所在機器IP地址

前段時間做定時任務的時候,需要在線上的服務器中的某一臺執行定時任務,沒有找到更好的方法,就想用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;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章