ping.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. _, err := net.LookupHost(TEST_URL1)
  21. return err == nil
  22. }
  23. func test2() bool {
  24. ctx, cancel := context.WithTimeout(context.Background(), TEST_TIMEOUT)
  25. defer cancel()
  26. cmd := exec.CommandContext(ctx, "ping", "-c", "3", TEST_HOST)
  27. out, err := cmd.CombinedOutput()
  28. if err != nil {
  29. return false
  30. }
  31. return strings.Contains(strings.ToLower(string(out)), "ttl=")
  32. }
  33. func test3() bool {
  34. conn, err := net.DialTimeout("tcp", TEST_HOST+":53", TEST_TIMEOUT)
  35. if err != nil {
  36. return false
  37. }
  38. conn.Close()
  39. return true
  40. }
  41. func test4() bool {
  42. client := http.Client{
  43. Timeout: TEST_TIMEOUT,
  44. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  45. return http.ErrUseLastResponse
  46. },
  47. }
  48. resp, err := client.Head(TEST_URL2)
  49. if err != nil {
  50. return false
  51. }
  52. resp.Body.Close()
  53. return true
  54. }
  55. func CheckNetwork() (dnsOK, pingOK, tcpOK, httpOK bool) {
  56. bOK1 := test1()
  57. bOK3 := test3()
  58. bOK4 := test4()
  59. bOK2 := test2() || bOK3 || bOK4
  60. return bOK1, bOK2, bOK3, bOK4
  61. }