wrapper.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package icmp
  2. import (
  3. "net"
  4. "runtime"
  5. "time"
  6. "golang.org/x/net/icmp"
  7. "golang.org/x/net/ipv4"
  8. "golang.org/x/net/ipv6"
  9. )
  10. type icmpConn struct {
  11. c *icmp.PacketConn
  12. ttl int
  13. }
  14. func (c *icmpConn) Close() error {
  15. return c.c.Close()
  16. }
  17. func (c *icmpConn) SetTTL(ttl int) {
  18. c.ttl = ttl
  19. }
  20. func (c *icmpConn) SetReadDeadline(t time.Time) error {
  21. return c.c.SetReadDeadline(t)
  22. }
  23. func (c *icmpConn) WriteTo(b []byte, dst net.Addr) (int, error) {
  24. if c.c.IPv6PacketConn() != nil {
  25. if err := c.c.IPv6PacketConn().SetHopLimit(c.ttl); err != nil {
  26. return 0, err
  27. }
  28. }
  29. if c.c.IPv4PacketConn() != nil {
  30. if err := c.c.IPv4PacketConn().SetTTL(c.ttl); err != nil {
  31. return 0, err
  32. }
  33. }
  34. return c.c.WriteTo(b, dst)
  35. }
  36. type icmpv4Conn struct {
  37. icmpConn
  38. }
  39. func (c *icmpv4Conn) SetFlagTTL() error {
  40. err := c.c.IPv4PacketConn().SetControlMessage(ipv4.FlagTTL, true)
  41. if runtime.GOOS == "windows" {
  42. return nil
  43. }
  44. return err
  45. }
  46. func (c *icmpv4Conn) ReadFrom(b []byte) (int, int, net.Addr, error) {
  47. ttl := -1
  48. n, cm, src, err := c.c.IPv4PacketConn().ReadFrom(b)
  49. if cm != nil {
  50. ttl = cm.TTL
  51. }
  52. return n, ttl, src, err
  53. }
  54. func (c icmpv4Conn) ICMPRequestType() Type {
  55. return ipv4.ICMPTypeEcho
  56. }
  57. type icmpV6Conn struct {
  58. icmpConn
  59. }
  60. func (c *icmpV6Conn) SetFlagTTL() error {
  61. err := c.c.IPv6PacketConn().SetControlMessage(ipv6.FlagHopLimit, true)
  62. if runtime.GOOS == "windows" {
  63. return nil
  64. }
  65. return err
  66. }
  67. func (c *icmpV6Conn) ReadFrom(b []byte) (int, int, net.Addr, error) {
  68. ttl := -1
  69. n, cm, src, err := c.c.IPv6PacketConn().ReadFrom(b)
  70. if cm != nil {
  71. ttl = cm.HopLimit
  72. }
  73. return n, ttl, src, err
  74. }
  75. func (c icmpV6Conn) ICMPRequestType() Type {
  76. return ipv6.ICMPTypeEchoRequest
  77. }