如何在容器内部通过Docker API获取容器的MAC地址
Got it, let's walk through exactly how to fetch a running container's MAC address using nothing but the Docker API—no workarounds, no exec-ing into the container, just pure API calls.
Step 1: Get your container's identifier
First, you need either the container's ID or its friendly name. If you don't have it already, run docker ps to list all running containers and grab the value you need from the first (ID) or last (NAMES) column.
Step 2: Call the Docker API's container details endpoint
The Docker API exposes container metadata via the /containers/{id}/json endpoint. Since the API is usually accessible via a Unix socket (on Linux/macOS) or a TCP port (Windows), here's how to hit it:
For Linux/macOS (Unix socket):
curl --unix-socket /var/run/docker.sock http://localhost/containers/<container_id_or_name>/json
For Windows (TCP socket, assuming default setup):
curl http://localhost:2375/containers/<container_id_or_name>/json
Step 3: Extract the MAC address from the response
The JSON response will have a NetworkSettings object, and inside that a Networks object that maps each connected network to its details. Each network entry includes the MacAddress field.
If your container is only connected to the default
bridgenetwork, you can target that directly:# Using jq to filter the output (install jq if you don't have it) curl --unix-socket /var/run/docker.sock http://localhost/containers/<container_id_or_name>/json | jq '.NetworkSettings.Networks.bridge.MacAddress'If your container is connected to multiple networks, you can list all MAC addresses with:
curl --unix-socket /var/run/docker.sock http://localhost/containers/<container_id_or_name>/json | jq '.NetworkSettings.Networks | to_entries[] | "\(.key): \(.value.MacAddress)"'
Notes to keep in mind
- Make sure your user has permissions to access the Docker socket (on Linux, you might need to prefix commands with
sudoor add your user to thedockergroup). - The Docker API version is backward compatible for this endpoint—you don't need to specify a version tag unless you're using a very old Docker installation.
- If you're using a programming language (Python, Go, etc.), you can use the official Docker SDKs to call this endpoint and parse the response programmatically instead of using curl.
内容的提问来源于stack exchange,提问作者Saboo

