tcping.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "net"
  7. "net/http"
  8. "sync"
  9. "time"
  10. "github.com/VividCortex/ewma"
  11. )
  12. //bool connectionSucceed float32 time
  13. func tcping(ip net.IPAddr, tcpPort int) (bool, time.Duration) {
  14. startTime := time.Now()
  15. fullAddress := fmt.Sprintf("%s:%d", ip.String(), tcpPort)
  16. //fmt.Println(ip.String())
  17. if ipv6Mode { // IPv6 需要加上 []
  18. fullAddress = fmt.Sprintf("[%s]:%d", ip.String(), tcpPort)
  19. }
  20. conn, err := net.DialTimeout("tcp", fullAddress, tcpConnectTimeout)
  21. if err != nil {
  22. return false, 0
  23. }
  24. defer conn.Close()
  25. duration := time.Since(startTime)
  26. return true, duration
  27. }
  28. //pingReceived pingTotalTime
  29. func checkConnection(ip net.IPAddr, tcpPort int) (pingRecv int, pingTime time.Duration) {
  30. for i := 1; i <= failTime; i++ {
  31. pingSucceed, pingTimeCurrent := tcping(ip, tcpPort)
  32. if pingSucceed {
  33. pingRecv++
  34. pingTime += pingTimeCurrent
  35. }
  36. }
  37. return
  38. }
  39. //return Success packetRecv averagePingTime specificIPAddr
  40. func tcpingHandler(ip net.IPAddr, tcpPort, pingCount int, progressHandler func(e progressEvent)) (bool, int, time.Duration, net.IPAddr) {
  41. ipCanConnect := false
  42. pingRecv := 0
  43. var pingTime time.Duration
  44. for !ipCanConnect {
  45. pingRecvCurrent, pingTimeCurrent := checkConnection(ip, tcpPort)
  46. if pingRecvCurrent != 0 {
  47. ipCanConnect = true
  48. pingRecv = pingRecvCurrent
  49. pingTime = pingTimeCurrent
  50. } else {
  51. ip.IP[15]++
  52. if ip.IP[15] == 0 {
  53. break
  54. }
  55. break
  56. }
  57. }
  58. if !ipCanConnect {
  59. progressHandler(NoAvailableIPFound)
  60. return false, 0, 0, net.IPAddr{}
  61. }
  62. progressHandler(AvailableIPFound)
  63. for i := failTime; i < pingCount; i++ {
  64. pingSuccess, pingTimeCurrent := tcping(ip, tcpPort)
  65. progressHandler(NormalPing)
  66. if pingSuccess {
  67. pingRecv++
  68. pingTime += pingTimeCurrent
  69. }
  70. }
  71. return true, pingRecv, pingTime / time.Duration(pingRecv), ip
  72. }
  73. func tcpingGoroutine(wg *sync.WaitGroup, mutex *sync.Mutex, ip net.IPAddr, tcpPort int, pingCount int, csv *[]CloudflareIPData, control chan bool, progressHandler func(e progressEvent)) {
  74. defer wg.Done()
  75. success, pingRecv, pingTimeAvg, currentIP := tcpingHandler(ip, tcpPort, pingCount, progressHandler)
  76. if success {
  77. mutex.Lock()
  78. var cfdata CloudflareIPData
  79. cfdata.ip = currentIP
  80. cfdata.pingReceived = pingRecv
  81. cfdata.pingTime = pingTimeAvg
  82. cfdata.pingCount = pingCount
  83. *csv = append(*csv, cfdata)
  84. mutex.Unlock()
  85. }
  86. <-control
  87. }
  88. func GetDialContextByAddr(fakeSourceAddr string) func(ctx context.Context, network, address string) (net.Conn, error) {
  89. return func(ctx context.Context, network, address string) (net.Conn, error) {
  90. c, e := (&net.Dialer{}).DialContext(ctx, network, fakeSourceAddr)
  91. return c, e
  92. }
  93. }
  94. //bool : can download,float32 downloadSpeed
  95. func DownloadSpeedHandler(ip net.IPAddr) (bool, float32) {
  96. var client = http.Client{
  97. Transport: nil,
  98. CheckRedirect: nil,
  99. Jar: nil,
  100. Timeout: downloadTestTime,
  101. }
  102. var fullAddress string
  103. if ipv6Mode { // IPv6 需要加上 []
  104. fullAddress = "[" + ip.String() + "]:443"
  105. } else {
  106. fullAddress = ip.String() + ":443"
  107. }
  108. client.Transport = &http.Transport{
  109. DialContext: GetDialContextByAddr(fullAddress),
  110. }
  111. response, err := client.Get(url)
  112. if err != nil {
  113. return false, 0
  114. }
  115. defer response.Body.Close()
  116. if response.StatusCode != 200 {
  117. return false, 0
  118. }
  119. timeStart := time.Now()
  120. timeEnd := timeStart.Add(downloadTestTime)
  121. contentLength := response.ContentLength
  122. buffer := make([]byte, downloadBufferSize)
  123. var (
  124. contentRead int64 = 0
  125. timeSlice = downloadTestTime / 100
  126. timeCounter = 1
  127. lastContentRead int64 = 0
  128. )
  129. var nextTime = timeStart.Add(timeSlice * time.Duration(timeCounter))
  130. e := ewma.NewMovingAverage()
  131. for contentLength != contentRead {
  132. var currentTime = time.Now()
  133. if currentTime.After(nextTime) {
  134. timeCounter++
  135. nextTime = timeStart.Add(timeSlice * time.Duration(timeCounter))
  136. e.Add(float64(contentRead - lastContentRead))
  137. lastContentRead = contentRead
  138. }
  139. if currentTime.After(timeEnd) {
  140. break
  141. }
  142. bufferRead, err := response.Body.Read(buffer)
  143. contentRead += int64(bufferRead)
  144. if err != nil {
  145. if err != io.EOF {
  146. break
  147. }
  148. e.Add(float64(contentRead-lastContentRead) / (float64(nextTime.Sub(currentTime)) / float64(timeSlice)))
  149. }
  150. }
  151. return true, float32(e.Value()) / (float32(downloadTestTime.Seconds()) / 120)
  152. }