java獲取docker、linux、windows的IP


代碼,依賴hutool工具

hostip=`ifconfig eth0 | grep inet |  awk '{print $2}' | awk -F: '{print $2}'`
#docker run --name java_app --net=host -d  --env hostip="${hostip}"  java:*** -jar hello.jar

java代碼

public static final String IP;
	static {

		// docker 容器啟動,獲得不到宿主機的ip,通過shell腳本的環境變量傳遞。
		String hostip = SystemUtil.get("hostip");
		// 獲取本機IP
		if (StrUtil.isBlank(hostip)) {
			OsInfo osInfo = SystemUtil.getOsInfo();
			if (osInfo.isLinux()) {
				NetworkInterface eth0 = NetUtil.getNetworkInterface("eth0");
				List<InterfaceAddress> interfaceAddresses = eth0.getInterfaceAddresses();
				hostip = interfaceAddresses.get(0).getAddress().getHostAddress();
			} else if (osInfo.isMac()) {
				hostip = NetUtil.getLocalMacAddress();
			} else if (osInfo.isWindows()){
				HostInfo hostInfo = SystemUtil.getHostInfo();
				hostip = hostInfo.getAddress();
			}else{
				hostip = "ip未識別系統";
			}

		}



		IP = hostip;
        }

參考資料


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM