packetconn.go 1.9 KB

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