ping.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package netmgrd
  2. import (
  3. "context"
  4. "net"
  5. "net/http"
  6. "os/exec"
  7. "strings"
  8. "time"
  9. )
  10. const (
  11. ///////////////////////////////////////
  12. // 白名单联网检测地址
  13. TEST_URL1 = "www.aliyun.com"
  14. TEST_URL2 = "http://8.136.98.49"
  15. TEST_HOST = "223.5.5.5" // 阿里云DNS主机
  16. ///////////////////////////////////////
  17. TEST_TIMEOUT = 5 * time.Second
  18. )
  19. func test1() bool {
  20. ctx, cancel := context.WithTimeout(context.Background(), TEST_TIMEOUT)
  21. defer cancel()
  22. addrs, err := net.DefaultResolver.LookupHost(ctx, TEST_URL1)
  23. return err == nil && len(addrs) > 0
  24. }
  25. func test2() bool {
  26. ctx, cancel := context.WithTimeout(context.Background(), TEST_TIMEOUT)
  27. defer cancel()
  28. cmd := exec.CommandContext(ctx, "ping", "-c", "3", "-W", "3", TEST_HOST)
  29. out, err := cmd.CombinedOutput()
  30. if err != nil {
  31. return false
  32. }
  33. return strings.Contains(strings.ToLower(string(out)), "ttl=")
  34. }
  35. func test3() bool {
  36. conn, err := net.DialTimeout("tcp", TEST_HOST+":53", TEST_TIMEOUT)
  37. if err != nil {
  38. return false
  39. }
  40. conn.Close()
  41. return true
  42. }
  43. func test4() (bool, time.Time) { // HTTP访问测试(不跟随重定向)
  44. client := http.Client{
  45. Timeout: TEST_TIMEOUT,
  46. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  47. return http.ErrUseLastResponse
  48. },
  49. }
  50. resp, err := client.Head(TEST_URL2)
  51. if err != nil {
  52. return false, time.Time{}
  53. }
  54. defer resp.Body.Close()
  55. date := resp.Header.Get("Date")
  56. if date == "" {
  57. return true, time.Time{}
  58. }
  59. t, err := time.Parse(http.TimeFormat, date)
  60. if err != nil {
  61. return true, time.Time{}
  62. }
  63. return true, t
  64. }
  65. func CheckNetwork() (dnsOK, pingOK, tcpOK, httpOK bool, httpTime time.Time) {
  66. bOK1 := test1()
  67. bOK3 := test3()
  68. bOK4, httpDate := test4()
  69. bOK2 := bOK3 || bOK4 || test2()
  70. return bOK1, bOK2, bOK3, bOK4, httpDate
  71. }