系统相关
首页 > 系统相关> > java获取docker、linux、windows的IP

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;
        }

参考资料

标签:osInfo,java,windows,IP,ip,hostip,eth0
来源: https://www.cnblogs.com/wlh1995/p/14251250.html