ping.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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://www.aliyun.com"
  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 { // 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
  53. }
  54. defer resp.Body.Close()
  55. return true
  56. }
  57. func CheckNetwork() (dnsOK, pingOK, tcpOK, httpOK bool) {
  58. bOK1 := test1()
  59. bOK3 := test3()
  60. bOK4 := test4()
  61. bOK2 := bOK3 || bOK4 || test2()
  62. return bOK1, bOK2, bOK3, bOK4
  63. }