github.com/portworx/docker@v1.12.1/api/client/container/port.go (about)

     1  package container
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"golang.org/x/net/context"
     8  
     9  	"github.com/docker/docker/api/client"
    10  	"github.com/docker/docker/cli"
    11  	"github.com/docker/go-connections/nat"
    12  	"github.com/spf13/cobra"
    13  )
    14  
    15  type portOptions struct {
    16  	container string
    17  
    18  	port string
    19  }
    20  
    21  // NewPortCommand creats a new cobra.Command for `docker port`
    22  func NewPortCommand(dockerCli *client.DockerCli) *cobra.Command {
    23  	var opts portOptions
    24  
    25  	cmd := &cobra.Command{
    26  		Use:   "port CONTAINER [PRIVATE_PORT[/PROTO]]",
    27  		Short: "List port mappings or a specific mapping for the container",
    28  		Args:  cli.RequiresRangeArgs(1, 2),
    29  		RunE: func(cmd *cobra.Command, args []string) error {
    30  			opts.container = args[0]
    31  			if len(args) > 1 {
    32  				opts.port = args[1]
    33  			}
    34  			return runPort(dockerCli, &opts)
    35  		},
    36  	}
    37  	cmd.SetFlagErrorFunc(flagErrorFunc)
    38  
    39  	return cmd
    40  }
    41  
    42  func runPort(dockerCli *client.DockerCli, opts *portOptions) error {
    43  	ctx := context.Background()
    44  
    45  	c, err := dockerCli.Client().ContainerInspect(ctx, opts.container)
    46  	if err != nil {
    47  		return err
    48  	}
    49  
    50  	if opts.port != "" {
    51  		port := opts.port
    52  		proto := "tcp"
    53  		parts := strings.SplitN(port, "/", 2)
    54  
    55  		if len(parts) == 2 && len(parts[1]) != 0 {
    56  			port = parts[0]
    57  			proto = parts[1]
    58  		}
    59  		natPort := port + "/" + proto
    60  		newP, err := nat.NewPort(proto, port)
    61  		if err != nil {
    62  			return err
    63  		}
    64  		if frontends, exists := c.NetworkSettings.Ports[newP]; exists && frontends != nil {
    65  			for _, frontend := range frontends {
    66  				fmt.Fprintf(dockerCli.Out(), "%s:%s\n", frontend.HostIP, frontend.HostPort)
    67  			}
    68  			return nil
    69  		}
    70  		return fmt.Errorf("Error: No public port '%s' published for %s", natPort, opts.container)
    71  	}
    72  
    73  	for from, frontends := range c.NetworkSettings.Ports {
    74  		for _, frontend := range frontends {
    75  			fmt.Fprintf(dockerCli.Out(), "%s -> %s:%s\n", from, frontend.HostIP, frontend.HostPort)
    76  		}
    77  	}
    78  
    79  	return nil
    80  }