gpt4 book ai didi

java - 有没有办法使用java程序获取docker容器内的主机Mac和IP地址

转载 作者:行者123 更新时间:2023-12-01 16:13:26 26 4
gpt4 key购买 nike

我在系统上尝试了以下程序,它返回主机 IP 地址,但是当作为 docker 容器运行时,它给出容器 IP

public static Map<String, String> getMAC(){
Map<String, String> dataMap = new HashMap<>();
try{
InetAddress inetaddress=InetAddress.getLocalHost(); //Get LocalHost refrence
String ip = inetaddress.getHostAddress(); // Get Host IP Address
dataMap.put("ip", ip);
//get Network interface Refrence by InetAddress Refrence
NetworkInterface network = NetworkInterface.getByInetAddress(inetaddress);
byte[] macArray = network.getHardwareAddress(); //get Harware address Array
StringBuilder str = new StringBuilder();

// Convert Array to String
for (int i = 0; i < macArray.length; i++) {
str.append(String.format("%02X%s", macArray[i], (i < macArray.length - 1) ? "-" : ""));
}
String macAddress=str.toString();
dataMap.put("mac", macAddress);
//return dataMap; //return MAc Address
}
catch(Exception E){
E.printStackTrace(); //print Exception StackTrace
//return null;
}
return dataMap;
}

最佳答案

根据Docker docs ,您可以通过解析host.docker.internal来获取主机的IP地址。因此,尝试将 try block 中的第一行更改为:

InetAddress inetaddress=InetAddress.getByName("host.docker.internal");

This is for development purpose and will not work in a productionenvironment outside of Docker Desktop for Mac.

关于java - 有没有办法使用java程序获取docker容器内的主机Mac和IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62471032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com