github.com/portworx/docker@v1.12.1/integration-cli/docker_cli_nat_test.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "net" 7 "strings" 8 9 "github.com/docker/docker/pkg/integration/checker" 10 "github.com/go-check/check" 11 ) 12 13 func startServerContainer(c *check.C, msg string, port int) string { 14 name := "server" 15 cmd := []string{ 16 "-d", 17 "-p", fmt.Sprintf("%d:%d", port, port), 18 "busybox", 19 "sh", "-c", fmt.Sprintf("echo %q | nc -lp %d", msg, port), 20 } 21 c.Assert(waitForContainer(name, cmd...), check.IsNil) 22 return name 23 } 24 25 func getExternalAddress(c *check.C) net.IP { 26 iface, err := net.InterfaceByName("eth0") 27 if err != nil { 28 c.Skip(fmt.Sprintf("Test not running with `make test`. Interface eth0 not found: %v", err)) 29 } 30 31 ifaceAddrs, err := iface.Addrs() 32 c.Assert(err, check.IsNil) 33 c.Assert(ifaceAddrs, checker.Not(checker.HasLen), 0) 34 35 ifaceIP, _, err := net.ParseCIDR(ifaceAddrs[0].String()) 36 c.Assert(err, check.IsNil) 37 38 return ifaceIP 39 } 40 41 func getContainerLogs(c *check.C, containerID string) string { 42 out, _ := dockerCmd(c, "logs", containerID) 43 return strings.Trim(out, "\r\n") 44 } 45 46 func getContainerStatus(c *check.C, containerID string) string { 47 out := inspectField(c, containerID, "State.Running") 48 return out 49 } 50 51 func (s *DockerSuite) TestNetworkNat(c *check.C) { 52 testRequires(c, DaemonIsLinux, SameHostDaemon) 53 msg := "it works" 54 startServerContainer(c, msg, 8080) 55 endpoint := getExternalAddress(c) 56 conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", endpoint.String(), 8080)) 57 c.Assert(err, check.IsNil) 58 59 data, err := ioutil.ReadAll(conn) 60 conn.Close() 61 c.Assert(err, check.IsNil) 62 63 final := strings.TrimRight(string(data), "\n") 64 c.Assert(final, checker.Equals, msg) 65 } 66 67 func (s *DockerSuite) TestNetworkLocalhostTCPNat(c *check.C) { 68 testRequires(c, DaemonIsLinux, SameHostDaemon) 69 var ( 70 msg = "hi yall" 71 ) 72 startServerContainer(c, msg, 8081) 73 conn, err := net.Dial("tcp", "localhost:8081") 74 c.Assert(err, check.IsNil) 75 76 data, err := ioutil.ReadAll(conn) 77 conn.Close() 78 c.Assert(err, check.IsNil) 79 80 final := strings.TrimRight(string(data), "\n") 81 c.Assert(final, checker.Equals, msg) 82 } 83 84 func (s *DockerSuite) TestNetworkLoopbackNat(c *check.C) { 85 testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace) 86 msg := "it works" 87 startServerContainer(c, msg, 8080) 88 endpoint := getExternalAddress(c) 89 out, _ := dockerCmd(c, "run", "-t", "--net=container:server", "busybox", 90 "sh", "-c", fmt.Sprintf("stty raw && nc -w 5 %s 8080", endpoint.String())) 91 final := strings.TrimRight(string(out), "\n") 92 c.Assert(final, checker.Equals, msg) 93 }