tcping.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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. fmt.Println("failTime", failTime)
  65. pingSuccess, pingTimeCurrent := tcping(ip, tcpPort)
  66. progressHandler(NormalPing)
  67. if pingSuccess {
  68. pingRecv++
  69. pingTime += pingTimeCurrent
  70. }
  71. }
  72. return true, pingRecv, pingTime / time.Duration(pingRecv), ip
  73. }
  74. func tcpingGoroutine(wg *sync.WaitGroup, mutex *sync.Mutex, ip net.IPAddr, tcpPort int, pingCount int, csv *[]CloudflareIPData, control chan bool, progressHandler func(e progressEvent)) {
  75. defer wg.Done()
  76. // fmt.Println(ip.String())
  77. success, pingRecv, pingTimeAvg, currentIP := tcpingHandler(ip, tcpPort, pingCount, progressHandler)
  78. if success {
  79. mutex.Lock()
  80. var cfdata CloudflareIPData
  81. cfdata.ip = currentIP
  82. cfdata.pingReceived = pingRecv
  83. cfdata.pingTime = pingTimeAvg
  84. cfdata.pingCount = pingCount
  85. *csv = append(*csv, cfdata)
  86. mutex.Unlock()
  87. }
  88. // <-control
  89. }
  90. func GetDialContextByAddr(fakeSourceAddr string) func(ctx context.Context, network, address string) (net.Conn, error) {
  91. return func(ctx context.Context, network, address string) (net.Conn, error) {
  92. c, e := (&net.Dialer{}).DialContext(ctx, network, fakeSourceAddr)
  93. return c, e
  94. }
  95. }
  96. //bool : can download,float32 downloadSpeed
  97. func DownloadSpeedHandler(ip net.IPAddr) (bool, float32) {
  98. var client = http.Client{
  99. Transport: nil,
  100. CheckRedirect: nil,
  101. Jar: nil,
  102. Timeout: downloadTestTime,
  103. }
  104. var fullAddress string
  105. if ipv6Mode { // IPv6 需要加上 []
  106. fullAddress = "[" + ip.String() + "]:443"
  107. } else {
  108. fullAddress = ip.String() + ":443"
  109. }
  110. client.Transport = &http.Transport{
  111. DialContext: GetDialContextByAddr(fullAddress),
  112. }
  113. response, err := client.Get(url)
  114. if err != nil {
  115. return false, 0
  116. }
  117. defer response.Body.Close()
  118. if response.StatusCode != 200 {
  119. return false, 0
  120. }
  121. timeStart := time.Now()
  122. timeEnd := timeStart.Add(downloadTestTime)
  123. contentLength := response.ContentLength
  124. buffer := make([]byte, downloadBufferSize)
  125. var (
  126. contentRead int64 = 0
  127. timeSlice = downloadTestTime / 100
  128. timeCounter = 1
  129. lastContentRead int64 = 0
  130. )
  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++
  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. }
  150. e.Add(float64(contentRead-lastContentRead) / (float64(nextTime.Sub(currentTime)) / float64(timeSlice)))
  151. }
  152. }
  153. return true, float32(e.Value()) / (float32(downloadTestTime.Seconds()) / 120)
  154. }