icmp_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package ipv4_test
  5. import (
  6. "net"
  7. "reflect"
  8. "runtime"
  9. "testing"
  10. "golang.org/x/net/ipv4"
  11. "golang.org/x/net/nettest"
  12. )
  13. var icmpStringTests = []struct {
  14. in ipv4.ICMPType
  15. out string
  16. }{
  17. {ipv4.ICMPTypeDestinationUnreachable, "destination unreachable"},
  18. {256, "<nil>"},
  19. }
  20. func TestICMPString(t *testing.T) {
  21. for _, tt := range icmpStringTests {
  22. s := tt.in.String()
  23. if s != tt.out {
  24. t.Errorf("got %s; want %s", s, tt.out)
  25. }
  26. }
  27. }
  28. func TestICMPFilter(t *testing.T) {
  29. switch runtime.GOOS {
  30. case "linux":
  31. default:
  32. t.Skipf("not supported on %s", runtime.GOOS)
  33. }
  34. var f ipv4.ICMPFilter
  35. for _, toggle := range []bool{false, true} {
  36. f.SetAll(toggle)
  37. for _, typ := range []ipv4.ICMPType{
  38. ipv4.ICMPTypeDestinationUnreachable,
  39. ipv4.ICMPTypeEchoReply,
  40. ipv4.ICMPTypeTimeExceeded,
  41. ipv4.ICMPTypeParameterProblem,
  42. } {
  43. f.Accept(typ)
  44. if f.WillBlock(typ) {
  45. t.Errorf("ipv4.ICMPFilter.Set(%v, false) failed", typ)
  46. }
  47. f.Block(typ)
  48. if !f.WillBlock(typ) {
  49. t.Errorf("ipv4.ICMPFilter.Set(%v, true) failed", typ)
  50. }
  51. }
  52. }
  53. }
  54. func TestSetICMPFilter(t *testing.T) {
  55. switch runtime.GOOS {
  56. case "linux":
  57. default:
  58. t.Skipf("not supported on %s", runtime.GOOS)
  59. }
  60. if !nettest.SupportsRawSocket() {
  61. t.Skipf("not supported on %s/%s", runtime.GOOS, runtime.GOARCH)
  62. }
  63. c, err := net.ListenPacket("ip4:icmp", "127.0.0.1")
  64. if err != nil {
  65. t.Fatal(err)
  66. }
  67. defer c.Close()
  68. p := ipv4.NewPacketConn(c)
  69. var f ipv4.ICMPFilter
  70. f.SetAll(true)
  71. f.Accept(ipv4.ICMPTypeEcho)
  72. f.Accept(ipv4.ICMPTypeEchoReply)
  73. if err := p.SetICMPFilter(&f); err != nil {
  74. t.Fatal(err)
  75. }
  76. kf, err := p.ICMPFilter()
  77. if err != nil {
  78. t.Fatal(err)
  79. }
  80. if !reflect.DeepEqual(kf, &f) {
  81. t.Fatalf("got %#v; want %#v", kf, f)
  82. }
  83. }