I have tried below program on System it returns the host IP address but when running as docker container its give container 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;
}
According to Docker docs , you can get the host's IP address by resolving host.docker.internal
. So try changing the first line in the try block to:
InetAddress inetaddress=InetAddress.getByName("host.docker.internal");
This is for development purpose and will not work in a production environment outside of Docker Desktop for Mac.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.