mirror of
https://github.com/containers/podman.git
synced 2025-07-15 03:02:52 +08:00
Add function to get IP address of a running container
Signed-off-by: Matthew Heon <matthew.heon@gmail.com> Closes: #192 Approved by: rhatdan
This commit is contained in:
@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
@ -297,6 +298,23 @@ func (c *Container) LogPath() string {
|
||||
return c.logPath()
|
||||
}
|
||||
|
||||
// IPAddress returns the IP address of the container
|
||||
// If the container does not have a network namespace, an error will be returned
|
||||
func (c *Container) IPAddress() (net.IP, error) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
if err := c.syncContainer(); err != nil {
|
||||
return nil, errors.Wrapf(err, "error updating container %s state", c.ID())
|
||||
}
|
||||
|
||||
if !c.config.CreateNetNS || c.state.NetNS == nil {
|
||||
return nil, errors.Wrapf(ErrInvalidArg, "container %s does not have a network namespace", c.ID())
|
||||
}
|
||||
|
||||
return c.runtime.getContainerIP(c)
|
||||
}
|
||||
|
||||
// ExitCode returns the exit code of the container as
|
||||
// an int32
|
||||
func (c *Container) ExitCode() (int32, error) {
|
||||
|
@ -113,6 +113,27 @@ func joinNetNS(path string) (ns.NetNS, error) {
|
||||
return ns, nil
|
||||
}
|
||||
|
||||
// Get a container's IP address
|
||||
func (r *Runtime) getContainerIP(ctr *Container) (net.IP, error) {
|
||||
if ctr.state.NetNS == nil {
|
||||
return nil, errors.Wrapf(ErrInvalidArg, "container %s has no network namespace, cannot get IP", ctr.ID())
|
||||
}
|
||||
|
||||
podNetwork := getPodNetwork(ctr.ID(), ctr.Name(), ctr.state.NetNS.Path(), ctr.config.PortMappings)
|
||||
|
||||
ipStr, err := r.netPlugin.GetPodNetworkStatus(podNetwork)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "error retrieving network status of container %s", ctr.ID())
|
||||
}
|
||||
|
||||
ip := net.ParseIP(ipStr)
|
||||
if ip == nil {
|
||||
return nil, errors.Wrapf(ErrInternal, "error parsing IP address %s for container %s", ipStr, ctr.ID())
|
||||
}
|
||||
|
||||
return ip, nil
|
||||
}
|
||||
|
||||
// Tear down a network namespace
|
||||
func (r *Runtime) teardownNetNS(ctr *Container) error {
|
||||
if ctr.state.NetNS == nil {
|
||||
|
Reference in New Issue
Block a user