github.com/tsuna/docker@v1.7.0-rc3/api/client/port.go (about)

     1  package client
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/docker/docker/nat"
     9  	flag "github.com/docker/docker/pkg/mflag"
    10  )
    11  
    12  // CmdPort lists port mappings for a container.
    13  // If a private port is specified, it also shows the public-facing port that is NATed to the private port.
    14  //
    15  // Usage: docker port CONTAINER [PRIVATE_PORT[/PROTO]]
    16  func (cli *DockerCli) CmdPort(args ...string) error {
    17  	cmd := cli.Subcmd("port", "CONTAINER [PRIVATE_PORT[/PROTO]]", "List port mappings for the CONTAINER, or lookup the public-facing port that\nis NAT-ed to the PRIVATE_PORT", true)
    18  	cmd.Require(flag.Min, 1)
    19  	cmd.ParseFlags(args, true)
    20  
    21  	stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil)
    22  	if err != nil {
    23  		return err
    24  	}
    25  
    26  	var c struct {
    27  		NetworkSettings struct {
    28  			Ports nat.PortMap
    29  		}
    30  	}
    31  
    32  	if err := json.NewDecoder(stream).Decode(&c); err != nil {
    33  		return err
    34  	}
    35  
    36  	if cmd.NArg() == 2 {
    37  		var (
    38  			port  = cmd.Arg(1)
    39  			proto = "tcp"
    40  			parts = strings.SplitN(port, "/", 2)
    41  		)
    42  
    43  		if len(parts) == 2 && len(parts[1]) != 0 {
    44  			port = parts[0]
    45  			proto = parts[1]
    46  		}
    47  		natPort := port + "/" + proto
    48  		if frontends, exists := c.NetworkSettings.Ports[nat.Port(port+"/"+proto)]; exists && frontends != nil {
    49  			for _, frontend := range frontends {
    50  				fmt.Fprintf(cli.out, "%s:%s\n", frontend.HostIp, frontend.HostPort)
    51  			}
    52  			return nil
    53  		}
    54  		return fmt.Errorf("Error: No public port '%s' published for %s", natPort, cmd.Arg(0))
    55  	}
    56  
    57  	for from, frontends := range c.NetworkSettings.Ports {
    58  		for _, frontend := range frontends {
    59  			fmt.Fprintf(cli.out, "%s -> %s:%s\n", from, frontend.HostIp, frontend.HostPort)
    60  		}
    61  	}
    62  
    63  	return nil
    64  }