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