docker_cli_nat_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. "os/exec"
  6. "strings"
  7. "testing"
  8. )
  9. func TestNetworkNat(t *testing.T) {
  10. iface, err := net.InterfaceByName("eth0")
  11. if err != nil {
  12. t.Skipf("Test not running with `make test`. Interface eth0 not found: %s", err)
  13. }
  14. ifaceAddrs, err := iface.Addrs()
  15. if err != nil || len(ifaceAddrs) == 0 {
  16. t.Fatalf("Error retrieving addresses for eth0: %v (%d addresses)", err, len(ifaceAddrs))
  17. }
  18. ifaceIP, _, err := net.ParseCIDR(ifaceAddrs[0].String())
  19. if err != nil {
  20. t.Fatalf("Error retrieving the up for eth0: %s", err)
  21. }
  22. runCmd := exec.Command(dockerBinary, "run", "-dt", "-p", "8080:8080", "busybox", "nc", "-lp", "8080")
  23. out, _, err := runCommandWithOutput(runCmd)
  24. if err != nil {
  25. t.Fatal(out, err)
  26. }
  27. cleanedContainerID := stripTrailingCharacters(out)
  28. runCmd = exec.Command(dockerBinary, "run", "busybox", "sh", "-c", fmt.Sprintf("echo hello world | nc -w 30 %s 8080", ifaceIP))
  29. out, _, err = runCommandWithOutput(runCmd)
  30. if err != nil {
  31. t.Fatal(out, err)
  32. }
  33. runCmd = exec.Command(dockerBinary, "logs", cleanedContainerID)
  34. out, _, err = runCommandWithOutput(runCmd)
  35. if err != nil {
  36. t.Fatalf("failed to retrieve logs for container: %s, %v", out, err)
  37. }
  38. out = strings.Trim(out, "\r\n")
  39. if expected := "hello world"; out != expected {
  40. t.Fatalf("Unexpected output. Expected: %q, received: %q for iface %s", expected, out, ifaceIP)
  41. }
  42. killCmd := exec.Command(dockerBinary, "kill", cleanedContainerID)
  43. if out, _, err = runCommandWithOutput(killCmd); err != nil {
  44. t.Fatalf("failed to kill container: %s, %v", out, err)
  45. }
  46. deleteAllContainers()
  47. logDone("network - make sure nat works through the host")
  48. }