github.com/a4a881d4/docker@v1.9.0-rc2/api/client/port.go (about)

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