example_test.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 icmp_test
  5. import (
  6. "log"
  7. "net"
  8. "os"
  9. "runtime"
  10. "golang.org/x/net/icmp"
  11. "golang.org/x/net/ipv6"
  12. )
  13. func ExamplePacketConn_nonPrivilegedPing() {
  14. switch runtime.GOOS {
  15. case "darwin":
  16. case "linux":
  17. log.Println("you may need to adjust the net.ipv4.ping_group_range kernel state")
  18. default:
  19. log.Println("not supported on", runtime.GOOS)
  20. return
  21. }
  22. c, err := icmp.ListenPacket("udp6", "fe80::1%en0")
  23. if err != nil {
  24. log.Fatal(err)
  25. }
  26. defer c.Close()
  27. wm := icmp.Message{
  28. Type: ipv6.ICMPTypeEchoRequest, Code: 0,
  29. Body: &icmp.Echo{
  30. ID: os.Getpid() & 0xffff, Seq: 1,
  31. Data: []byte("HELLO-R-U-THERE"),
  32. },
  33. }
  34. wb, err := wm.Marshal(nil)
  35. if err != nil {
  36. log.Fatal(err)
  37. }
  38. if _, err := c.WriteTo(wb, &net.UDPAddr{IP: net.ParseIP("ff02::1"), Zone: "en0"}); err != nil {
  39. log.Fatal(err)
  40. }
  41. rb := make([]byte, 1500)
  42. n, peer, err := c.ReadFrom(rb)
  43. if err != nil {
  44. log.Fatal(err)
  45. }
  46. rm, err := icmp.ParseMessage(58, rb[:n])
  47. if err != nil {
  48. log.Fatal(err)
  49. }
  50. switch rm.Type {
  51. case ipv6.ICMPTypeEchoReply:
  52. log.Printf("got reflection from %v", peer)
  53. default:
  54. log.Printf("got %+v; want echo reply", rm)
  55. }
  56. }