netstat_test.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. //go:build darwin && !ios
  4. package portlist
  5. import (
  6. "bufio"
  7. "encoding/json"
  8. "fmt"
  9. "strings"
  10. "testing"
  11. "go4.org/mem"
  12. )
  13. func TestParsePort(t *testing.T) {
  14. type InOut struct {
  15. in string
  16. expect int
  17. }
  18. tests := []InOut{
  19. {"1.2.3.4:5678", 5678},
  20. {"0.0.0.0.999", 999},
  21. {"1.2.3.4:*", 0},
  22. {"5.5.5.5:0", 0},
  23. {"[1::2]:5", 5},
  24. {"[1::2].5", 5},
  25. {"gibberish", -1},
  26. }
  27. for _, io := range tests {
  28. got := parsePort(mem.S(io.in))
  29. if got != io.expect {
  30. t.Fatalf("input:%#v expect:%v got:%v\n", io.in, io.expect, got)
  31. }
  32. }
  33. }
  34. const netstatOutput = `
  35. // macOS
  36. tcp4 0 0 *.23 *.* LISTEN
  37. tcp6 0 0 *.24 *.* LISTEN
  38. tcp4 0 0 *.8185 *.* LISTEN
  39. tcp4 0 0 127.0.0.1.8186 *.* LISTEN
  40. tcp6 0 0 ::1.8187 *.* LISTEN
  41. tcp4 0 0 127.1.2.3.8188 *.* LISTEN
  42. udp6 0 0 *.106 *.*
  43. udp4 0 0 *.104 *.*
  44. udp46 0 0 *.146 *.*
  45. `
  46. func TestParsePortsNetstat(t *testing.T) {
  47. for _, loopBack := range [...]bool{false, true} {
  48. t.Run(fmt.Sprintf("loopback_%v", loopBack), func(t *testing.T) {
  49. want := List{
  50. {"tcp", 23, "", 0},
  51. {"tcp", 24, "", 0},
  52. {"udp", 104, "", 0},
  53. {"udp", 106, "", 0},
  54. {"udp", 146, "", 0},
  55. {"tcp", 8185, "", 0}, // but not 8186, 8187, 8188 on localhost, when loopback is false
  56. }
  57. if loopBack {
  58. want = append(want,
  59. Port{"tcp", 8186, "", 0},
  60. Port{"tcp", 8187, "", 0},
  61. Port{"tcp", 8188, "", 0},
  62. )
  63. }
  64. pl, err := appendParsePortsNetstat(nil, bufio.NewReader(strings.NewReader(netstatOutput)), loopBack)
  65. if err != nil {
  66. t.Fatal(err)
  67. }
  68. pl = sortAndDedup(pl)
  69. jgot, _ := json.MarshalIndent(pl, "", "\t")
  70. jwant, _ := json.MarshalIndent(want, "", "\t")
  71. if len(pl) != len(want) {
  72. t.Fatalf("Got:\n%s\n\nWant:\n%s\n", jgot, jwant)
  73. }
  74. for i := range pl {
  75. if pl[i] != want[i] {
  76. t.Errorf("row#%d\n got: %+v\n\nwant: %+v\n",
  77. i, pl[i], want[i])
  78. t.Fatalf("Got:\n%s\n\nWant:\n%s\n", jgot, jwant)
  79. }
  80. }
  81. })
  82. }
  83. }