tcping.go 4.7 KB

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