docker容器通過ping直接運行獲取公網IP

通過容器獲取本機的公網ip  可以用本地IP 多服務註冊中心

把命令改居ping  執行可以拿到不同的服務器信息

  public static String getIfconfigIP()
    {
        BufferedReader in = null;
        String outline = "";
        // timeOut window爲ms linux 爲s
        Runtime r = Runtime.getRuntime(); // 將要執行的ping命令,此命令是windows格式的命令
        String pingCommand = "  curl ifconfig.me  ";// windows系統
        String os = System.getProperty("os.name").toLowerCase();
        if (os.indexOf("linux") >= 0)
        {
            pingCommand = "  curl ifconfig.me ";
        }
        if (os.indexOf("mac") >= 0)
        {
            pingCommand = " curl ifconfig.me ";
        }
        try
        { // 執行命令並獲取輸出
            System.out.println(pingCommand);
            Process p = r.exec(pingCommand);
            if (p == null)
            {
                return "cmd failed";
            }
            in = new BufferedReader(new InputStreamReader(p.getInputStream())); // 逐行檢查輸出,計算類似出現=23ms
            // TTL=62字樣的次數
            int connectedCount = 0;
            String line = null;

            while ((line = in.readLine()) != null)
            {
                outline += line;
            }
            return outline;
        }
        catch (Exception ex)
        {
            ex.printStackTrace(); // 出現異常則返回假
            return outline;
        }
        finally
        {
            try
            {
                in.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }

    }

 

docker 裏面的ip是假的,如何在docker 內運行的程序獲取宿主主機的ip地址呢  下面給了我一些提示

p = require('child_process')
      .spawnSync('curl', ['ifconfig.io'])
      .stdout
      .toString()
      .trim()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章