tcpping.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package nettools
  2. import (
  3. "fmt"
  4. "golang.org/x/net/context"
  5. "net"
  6. "strconv"
  7. "time"
  8. )
  9. type TcpPingResult struct {
  10. Time int
  11. Err error
  12. IP net.IP
  13. }
  14. func (tcpR *TcpPingResult) Result() int {
  15. return tcpR.Time
  16. }
  17. func (tcpR *TcpPingResult) Error() error {
  18. return tcpR.Err
  19. }
  20. func (tcpR *TcpPingResult) String() string {
  21. if tcpR.Err != nil {
  22. return fmt.Sprintf("%s", tcpR.Err)
  23. } else {
  24. return fmt.Sprintf("%s: time=%d ms", tcpR.IP.String(), tcpR.Time)
  25. }
  26. }
  27. type TcpPing struct {
  28. host string
  29. Port int
  30. Timeout time.Duration
  31. ip net.IP
  32. }
  33. func (tcpC *TcpPing) SetHost(host string) {
  34. tcpC.host = host
  35. tcpC.ip = net.ParseIP(host)
  36. }
  37. func (tcpC *TcpPing) Host() string {
  38. return tcpC.host
  39. }
  40. func (tcpC *TcpPing) Ping() IPingResult {
  41. return tcpC.PingContext(context.Background())
  42. }
  43. func (tcpC *TcpPing) PingContext(ctx context.Context) IPingResult {
  44. ip := cloneIP(tcpC.ip)
  45. if ip == nil {
  46. var err error
  47. ip, err = LookupFunc(tcpC.host)
  48. if err != nil {
  49. return &TcpPingResult{0, err, nil}
  50. }
  51. }
  52. dialer := &net.Dialer{
  53. Timeout: tcpC.Timeout,
  54. KeepAlive: -1,
  55. }
  56. t0 := time.Now()
  57. conn, err := dialer.DialContext(ctx, "tcp", net.JoinHostPort(ip.String(), strconv.FormatUint(uint64(tcpC.Port), 10)))
  58. if err != nil {
  59. return &TcpPingResult{0, err, nil}
  60. }
  61. defer conn.Close()
  62. return &TcpPingResult{int(time.Now().Sub(t0).Milliseconds()), nil, ip}
  63. }
  64. func NewTcpPing(host string, port int, timeout time.Duration) *TcpPing {
  65. return &TcpPing{
  66. host: host,
  67. Port: port,
  68. Timeout: timeout,
  69. ip: net.ParseIP(host),
  70. }
  71. }
  72. var (
  73. _ IPing = (*TcpPing)(nil)
  74. _ IPingResult = (*TcpPingResult)(nil)
  75. )