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