├── ipv6.txt
├── ip.txt
├── go.mod
├── utils
├── progress.go
└── csv.go
├── go.sum
├── .github
└── workflows
│ └── build.yml
├── task
├── tcping.go
├── httping.go
├── download.go
└── ip.go
├── main.go
├── LICENSE
└── README.md
/ipv6.txt:
--------------------------------------------------------------------------------
1 | 2400:cb00::/32
2 | 2405:b500::/32
3 | 2405:8100::/32
4 | 2606:4700::/32
5 | 2803:f800::/32
6 | 2a06:98c0::/32
7 | 2a06:98c1::/32
8 | 2a06:98c2::/32
9 | 2a06:98c3::/32
10 | 2a06:98c4::/32
11 | 2a06:98c5::/32
12 | 2a06:98c6::/32
13 | 2a06:98c7::/32
14 | 2c0f:f248::/32
--------------------------------------------------------------------------------
/ip.txt:
--------------------------------------------------------------------------------
1 | 103.21.244.0/22
2 | 103.22.200.0/22
3 | 103.31.4.0/22
4 | 104.16.0.0/13
5 | 104.24.0.0/14
6 | 108.162.192.0/18
7 | 131.0.72.0/22
8 | 141.101.64.0/18
9 | 162.158.0.0/15
10 | 172.64.0.0/13
11 | 173.245.48.0/20
12 | 188.114.96.0/20
13 | 190.93.240.0/20
14 | 197.234.240.0/22
15 | 198.41.128.0/17
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/Ptechgithub/CloudflareScanner
2 |
3 | go 1.22.1
4 |
5 | require (
6 | github.com/VividCortex/ewma v1.2.0
7 | github.com/cheggaaa/pb/v3 v3.1.5
8 | )
9 |
10 | require (
11 | github.com/fatih/color v1.15.0 // indirect
12 | github.com/mattn/go-colorable v0.1.13 // indirect
13 | github.com/mattn/go-isatty v0.0.19 // indirect
14 | github.com/mattn/go-runewidth v0.0.15 // indirect
15 | github.com/rivo/uniseg v0.2.0 // indirect
16 | golang.org/x/sys v0.6.0 // indirect
17 | )
18 |
--------------------------------------------------------------------------------
/utils/progress.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "fmt"
5 | "time"
6 |
7 | "github.com/cheggaaa/pb/v3"
8 | )
9 |
10 | type Bar struct {
11 | pb *pb.ProgressBar
12 | }
13 |
14 | func NewBar(count int, MyStrStart, MyStrEnd string) *Bar {
15 | tmpl := fmt.Sprintf(`{{counters . }} {{ bar . "[" "-" (cycle . "↖" "↗" "↘" "↙" ) "_" "]"}} %s {{string . "MyStr" | green}} %s {{rtime . | blue}}`, MyStrStart, MyStrEnd)
16 | bar := pb.ProgressBarTemplate(tmpl).Start(count)
17 | return &Bar{pb: bar}
18 | }
19 |
20 | func (b *Bar) Grow(num int, MyStrVal string) {
21 | b.pb.Set("MyStr", MyStrVal).Add(num)
22 | }
23 |
24 | func (b *Bar) Done() {
25 | b.pb.Finish()
26 | }
27 |
28 | func main() {
29 | total := 100
30 | bar := NewBar(total, "Start", "End")
31 |
32 | for i := 0; i < total; i++ {
33 | bar.Grow(1, fmt.Sprintf("Progress %d/%d", i+1, total))
34 | time.Sleep(50 * time.Millisecond)
35 | }
36 |
37 | bar.Done()
38 | }
39 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/VividCortex/ewma v1.2.0 h1:f58SaIzcDXrSy3kWaHNvuJgJ3Nmz59Zji6XoJR/q1ow=
2 | github.com/VividCortex/ewma v1.2.0/go.mod h1:nz4BbCtbLyFDeC9SUHbtcT5644juEuWfUAUnGx7j5l4=
3 | github.com/cheggaaa/pb/v3 v3.1.5 h1:QuuUzeM2WsAqG2gMqtzaWithDJv0i+i6UlnwSCI4QLk=
4 | github.com/cheggaaa/pb/v3 v3.1.5/go.mod h1:CrxkeghYTXi1lQBEI7jSn+3svI3cuc19haAj6jM60XI=
5 | github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs=
6 | github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw=
7 | github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM=
8 | github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE=
9 | github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
10 | github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
11 | github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
12 | github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
13 | github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
14 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
15 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
16 | github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
17 | github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
18 | github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
19 | github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
20 | github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
21 | github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
22 | golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
23 | golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
24 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
25 | golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
26 | golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
27 |
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: CloudflareScanner
2 |
3 | on:
4 | workflow_dispatch:
5 | release:
6 | types: [published]
7 |
8 | jobs:
9 | build:
10 | permissions:
11 | contents: write
12 | strategy:
13 | fail-fast: false
14 | matrix:
15 | include:
16 | - goos: darwin
17 | goarch: amd64
18 | - goos: darwin
19 | goarch: arm64
20 |
21 | - goos: android
22 | goarch: arm64
23 |
24 | - goos: linux
25 | goarch: amd64
26 | - goos: linux
27 | goarch: arm64
28 | - goos: linux
29 | goarch: riscv64
30 | - goos: linux
31 | goarch: mips64
32 | - goos: linux
33 | goarch: mips64le
34 | - goos: linux
35 | goarch: arm
36 | goarm: 7
37 |
38 | - goos: windows
39 | goarch: amd64
40 | - goos: windows
41 | goarch: arm64
42 |
43 | runs-on: ubuntu-latest
44 | env:
45 | GOOS: ${{ matrix.goos }}
46 | GOARCH: ${{ matrix.goarch }}
47 | GOARM: ${{ matrix.goarm }}
48 | CGO_ENABLED: 0
49 | version: "v2.2.5"
50 |
51 | steps:
52 | - name: Checkout codebase
53 | uses: actions/checkout@v4
54 |
55 | - name: Show workflow information
56 | run: |
57 | export _NAME=$GOOS-$GOARCH$GOARM$GOMIPS
58 | echo "GOOS: $GOOS, GOARCH: $GOARCH, GOARM: $GOARM, GOMIPS: $GOMIPS, RELEASE_NAME: $_NAME"
59 | echo "ASSET_NAME=$_NAME" >> $GITHUB_ENV
60 | echo "REF=${GITHUB_SHA::6}" >> $GITHUB_ENV
61 |
62 | - name: Set up Go
63 | uses: actions/setup-go@v5
64 | with:
65 | go-version: '1.21'
66 | check-latest: true
67 |
68 | - name: Build CloudflareScanner
69 | run: |
70 | go build -v -o build_assets/ -trimpath -ldflags "-s -w -X main.version=${version}" .
71 |
72 | - name: Copy ip.txt & ipv6.txt & README.md
73 | run: |
74 | cp ${GITHUB_WORKSPACE}/ip.txt ./build_assets/ip.txt
75 | cp ${GITHUB_WORKSPACE}/ipv6.txt ./build_assets/ipv6.txt
76 | cp ${GITHUB_WORKSPACE}/README.md ./build_assets/README.md
77 |
78 | - name: Create ZIP archive
79 | shell: bash
80 | run: |
81 | pushd ./build_assets || exit 1
82 | touch -mt $(date +%Y01010000) *
83 | zip -9vr ../CloudflareScanner_${{ env.ASSET_NAME }}.zip .
84 | popd || exit 1
85 |
86 | - name: Change the name
87 | run: |
88 | mv ./build_assets ./CloudflareScanner_${{ env.ASSET_NAME }}
89 |
90 | - name: Upload files to Artifacts
91 | uses: actions/upload-artifact@v4
92 | with:
93 | name: CloudflareScanner_${{ env.ASSET_NAME }}
94 | path: |
95 | ./CloudflareScanner_${{ env.ASSET_NAME }}/*
96 |
97 | - name: Upload binaries to release
98 | uses: svenstaro/upload-release-action@v2
99 | if: github.event_name == 'release'
100 | with:
101 | repo_token: ${{ secrets.GITHUB_TOKEN }}
102 | file: ./CloudflareScanner_${{ env.ASSET_NAME }}.zip*
103 | tag: ${{ github.ref }}
104 | file_glob: true
--------------------------------------------------------------------------------
/task/tcping.go:
--------------------------------------------------------------------------------
1 | package task
2 |
3 | import (
4 | "fmt"
5 | "net"
6 | "sort"
7 | "strconv"
8 | "sync"
9 | "time"
10 |
11 | "github.com/Ptechgithub/CloudflareScanner/utils"
12 | )
13 |
14 | const (
15 | tcpConnectTimeout = time.Second * 1
16 | maxRoutine = 1000
17 | defaultRoutines = 200
18 | defaultPort = 443
19 | defaultPingTimes = 4
20 | )
21 |
22 | var (
23 | Routines = defaultRoutines
24 | TCPPort int = defaultPort
25 | PingTimes int = defaultPingTimes
26 | )
27 |
28 | type Ping struct {
29 | wg *sync.WaitGroup
30 | m *sync.Mutex
31 | ips []*net.IPAddr
32 | csv utils.PingDelaySet
33 | control chan bool
34 | bar *utils.Bar
35 | }
36 |
37 | func checkPingDefault() {
38 | if Routines <= 0 {
39 | Routines = defaultRoutines
40 | }
41 | if TCPPort <= 0 || TCPPort >= 65535 {
42 | TCPPort = defaultPort
43 | }
44 | if PingTimes <= 0 {
45 | PingTimes = defaultPingTimes
46 | }
47 | }
48 |
49 | func NewPing() *Ping {
50 | checkPingDefault()
51 | ips := loadIPRanges()
52 | return &Ping{
53 | wg: &sync.WaitGroup{},
54 | m: &sync.Mutex{},
55 | ips: ips,
56 | csv: make(utils.PingDelaySet, 0),
57 | control: make(chan bool, Routines),
58 | bar: utils.NewBar(len(ips), "Available:", ""),
59 | }
60 | }
61 |
62 | func (p *Ping) Run() utils.PingDelaySet {
63 | if len(p.ips) == 0 {
64 | return p.csv
65 | }
66 | if Httping {
67 | fmt.Printf("Start latency test (Mode: HTTP, Port: %d, Range: %v ~ %v ms, Packet Loss: %.2f)\n", TCPPort, utils.InputMinDelay.Milliseconds(), utils.InputMaxDelay.Milliseconds(), utils.InputMaxLossRate)
68 | } else {
69 | fmt.Printf("Start latency test (Mode: TCP, Port: %d, Range: %v ~ %v ms, Packet Loss: %.2f)\n", TCPPort, utils.InputMinDelay.Milliseconds(), utils.InputMaxDelay.Milliseconds(), utils.InputMaxLossRate)
70 | }
71 | for _, ip := range p.ips {
72 | p.wg.Add(1)
73 | p.control <- false
74 | go p.start(ip)
75 | }
76 | p.wg.Wait()
77 | p.bar.Done()
78 | sort.Sort(p.csv)
79 | return p.csv
80 | }
81 |
82 | func (p *Ping) start(ip *net.IPAddr) {
83 | defer p.wg.Done()
84 | p.tcpingHandler(ip)
85 | <-p.control
86 | }
87 |
88 | // bool connectionSucceed float32 time
89 | func (p *Ping) tcping(ip *net.IPAddr) (bool, time.Duration) {
90 | startTime := time.Now()
91 | var fullAddress string
92 | if isIPv4(ip.String()) {
93 | fullAddress = fmt.Sprintf("%s:%d", ip.String(), TCPPort)
94 | } else {
95 | fullAddress = fmt.Sprintf("[%s]:%d", ip.String(), TCPPort)
96 | }
97 | conn, err := net.DialTimeout("tcp", fullAddress, tcpConnectTimeout)
98 | if err != nil {
99 | return false, 0
100 | }
101 | defer conn.Close()
102 | duration := time.Since(startTime)
103 | return true, duration
104 | }
105 |
106 | // pingReceived pingTotalTime
107 | func (p *Ping) checkConnection(ip *net.IPAddr) (recv int, totalDelay time.Duration) {
108 | if Httping {
109 | recv, totalDelay = p.httping(ip)
110 | return
111 | }
112 | for i := 0; i < PingTimes; i++ {
113 | if ok, delay := p.tcping(ip); ok {
114 | recv++
115 | totalDelay += delay
116 | }
117 | }
118 | return
119 | }
120 |
121 | func (p *Ping) appendIPData(data *utils.PingData) {
122 | p.m.Lock()
123 | defer p.m.Unlock()
124 | p.csv = append(p.csv, utils.CloudflareIPData{
125 | PingData: data,
126 | })
127 | }
128 |
129 | // handle tcping
130 | func (p *Ping) tcpingHandler(ip *net.IPAddr) {
131 | recv, totalDlay := p.checkConnection(ip)
132 | nowAble := len(p.csv)
133 | if recv != 0 {
134 | nowAble++
135 | }
136 | p.bar.Grow(1, strconv.Itoa(nowAble))
137 | if recv == 0 {
138 | return
139 | }
140 | data := &utils.PingData{
141 | IP: ip,
142 | Sended: PingTimes,
143 | Received: recv,
144 | Delay: totalDlay / time.Duration(recv),
145 | }
146 | p.appendIPData(data)
147 | }
148 |
--------------------------------------------------------------------------------
/task/httping.go:
--------------------------------------------------------------------------------
1 | package task
2 |
3 | import (
4 | //"crypto/tls"
5 | //"fmt"
6 | "io"
7 | "log"
8 | "net"
9 | "net/http"
10 | "regexp"
11 | "strings"
12 | "sync"
13 | "time"
14 | )
15 |
16 | var (
17 | Httping bool
18 | HttpingStatusCode int
19 | HttpingCFColo string
20 | HttpingCFColomap *sync.Map
21 | OutRegexp = regexp.MustCompile(`[A-Z]{3}`)
22 | )
23 |
24 | // pingReceived pingTotalTime
25 | func (p *Ping) httping(ip *net.IPAddr) (int, time.Duration) {
26 | hc := http.Client{
27 | Timeout: time.Second * 2,
28 | Transport: &http.Transport{
29 | DialContext: getDialContext(ip),
30 | //TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // Skip certificate verification
31 | },
32 | CheckRedirect: func(req *http.Request, via []*http.Request) error {
33 | return http.ErrUseLastResponse // Prevent redirection
34 | },
35 | }
36 |
37 | // First, access to obtain the HTTP status code and Cloudflare Colo
38 | {
39 | requ, err := http.NewRequest(http.MethodHead, URL, nil)
40 | if err != nil {
41 | return 0, 0
42 | }
43 | requ.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36")
44 | resp, err := hc.Do(requ)
45 | if err != nil {
46 | return 0, 0
47 | }
48 | defer resp.Body.Close()
49 |
50 | //fmt.Println("IP:", ip, "StatusCode:", resp.StatusCode, resp.Request.URL)
51 | // If the HTTP status code is unspecified or not compliant, only 200, 301, and 302 are considered successful HTTPing
52 | if HttpingStatusCode == 0 || HttpingStatusCode < 100 && HttpingStatusCode > 599 {
53 | if resp.StatusCode != 200 && resp.StatusCode != 301 && resp.StatusCode != 302 {
54 | return 0, 0
55 | }
56 | } else {
57 | if resp.StatusCode != HttpingStatusCode {
58 | return 0, 0
59 | }
60 | }
61 |
62 | io.Copy(io.Discard, resp.Body)
63 |
64 | // Only match airport codes if the region is specified
65 | if HttpingCFColo != "" {
66 | // Determine whether it is Cloudflare or AWS CloudFront based on the Server header value and set cfRay to the airport code of each
67 | cfRay := func() string {
68 | if resp.Header.Get("Server") == "cloudflare" {
69 | return resp.Header.Get("CF-RAY") // Example cf-ray: 7bd32409eda7b020-SJC
70 | }
71 | return resp.Header.Get("x-amz-cf-pop") // Example X-Amz-Cf-Pop: SIN52-P1
72 | }()
73 | colo := p.getColo(cfRay)
74 | if colo == "" { // If no airport code is matched or does not match the specified region, end the IP test directly
75 | return 0, 0
76 | }
77 | }
78 |
79 | }
80 |
81 | // Loop to calculate latency
82 | success := 0
83 | var delay time.Duration
84 | for i := 0; i < PingTimes; i++ {
85 | requ, err := http.NewRequest(http.MethodHead, URL, nil)
86 | if err != nil {
87 | log.Fatal("Unexpected error, please report:", err)
88 | return 0, 0
89 | }
90 | requ.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36")
91 | if i == PingTimes-1 {
92 | requ.Header.Set("Connection", "close")
93 | }
94 | startTime := time.Now()
95 | resp, err := hc.Do(requ)
96 | if err != nil {
97 | continue
98 | }
99 | success++
100 | io.Copy(io.Discard, resp.Body)
101 | _ = resp.Body.Close()
102 | duration := time.Since(startTime)
103 | delay += duration
104 |
105 | }
106 |
107 | return success, delay
108 |
109 | }
110 |
111 | func MapColoMap() *sync.Map {
112 | if HttpingCFColo == "" {
113 | return nil
114 | }
115 | // Convert the specified region airport code to uppercase and format it
116 | colos := strings.Split(strings.ToUpper(HttpingCFColo), ",")
117 | colomap := &sync.Map{}
118 | for _, colo := range colos {
119 | colomap.Store(colo, colo)
120 | }
121 | return colomap
122 | }
123 |
124 | func (p *Ping) getColo(b string) string {
125 | if b == "" {
126 | return ""
127 | }
128 | // Match and return the airport code
129 | out := OutRegexp.FindString(b)
130 |
131 | if HttpingCFColomap == nil {
132 | return out
133 | }
134 | // Match whether the airport code is for the specified region
135 | _, ok := HttpingCFColomap.Load(out)
136 | if ok {
137 | return out
138 | }
139 |
140 | return ""
141 | }
142 |
--------------------------------------------------------------------------------
/task/download.go:
--------------------------------------------------------------------------------
1 | package task
2 |
3 | import (
4 | "context"
5 | "fmt"
6 | "io"
7 | "net"
8 | "net/http"
9 | "sort"
10 | "strconv"
11 | "time"
12 |
13 | "github.com/Ptechgithub/CloudflareScanner/utils"
14 | "github.com/VividCortex/ewma"
15 | )
16 |
17 | const (
18 | bufferSize = 1024
19 | defaultURL = "https://cf.xiu2.xyz/url"
20 | defaultTimeout = 10 * time.Second
21 | defaultDisableDownload = false
22 | defaultTestNum = 10
23 | defaultMinSpeed float64 = 0.0
24 | )
25 |
26 | var (
27 | URL = defaultURL
28 | Timeout = defaultTimeout
29 | Disable = defaultDisableDownload
30 |
31 | TestCount = defaultTestNum
32 | MinSpeed = defaultMinSpeed
33 | )
34 |
35 | func checkDownloadDefault() {
36 | if URL == "" {
37 | URL = defaultURL
38 | }
39 | if Timeout <= 0 {
40 | Timeout = defaultTimeout
41 | }
42 | if TestCount <= 0 {
43 | TestCount = defaultTestNum
44 | }
45 | if MinSpeed <= 0.0 {
46 | MinSpeed = defaultMinSpeed
47 | }
48 | }
49 |
50 | func TestDownloadSpeed(ipSet utils.PingDelaySet) (speedSet utils.DownloadSpeedSet) {
51 | checkDownloadDefault()
52 | if Disable {
53 | return utils.DownloadSpeedSet(ipSet)
54 | }
55 | if len(ipSet) <= 0 {
56 | fmt.Println("\n[Info] The number of delay test IP addresses is 0, skipping download speed test.")
57 | return
58 | }
59 | testNum := TestCount
60 | if len(ipSet) < TestCount || MinSpeed > 0 {
61 | testNum = len(ipSet)
62 | }
63 | if testNum < TestCount {
64 | TestCount = testNum
65 | }
66 |
67 | fmt.Printf("Start download speed test (Minimum speed: %.2f MB/s, Number: %d, Queue: %d)\n", MinSpeed, TestCount, testNum)
68 | // Ensures that the length of the download speed progress bar matches the length of the latency progress bar (for OCD purposes)
69 | bar_a := len(strconv.Itoa(len(ipSet)))
70 | bar_b := " "
71 | for i := 0; i < bar_a; i++ {
72 | bar_b += " "
73 | }
74 | bar := utils.NewBar(TestCount, bar_b, "")
75 | for i := 0; i < testNum; i++ {
76 | speed := downloadHandler(ipSet[i].IP)
77 | ipSet[i].DownloadSpeed = speed
78 | // After measuring the download speed for each IP, filter the results based on the [minimum download speed] condition.
79 | if speed >= MinSpeed*1024*1024 {
80 | bar.Grow(1, "")
81 | speedSet = append(speedSet, ipSet[i])
82 | if len(speedSet) == TestCount {
83 | break
84 | }
85 | }
86 | }
87 | bar.Done()
88 | if len(speedSet) == 0 {
89 | speedSet = utils.DownloadSpeedSet(ipSet)
90 | }
91 | // Sorts the results by speed
92 | sort.Sort(speedSet)
93 | return
94 | }
95 |
96 | func getDialContext(ip *net.IPAddr) func(ctx context.Context, network, address string) (net.Conn, error) {
97 | var fakeSourceAddr string
98 | if isIPv4(ip.String()) {
99 | fakeSourceAddr = fmt.Sprintf("%s:%d", ip.String(), TCPPort)
100 | } else {
101 | fakeSourceAddr = fmt.Sprintf("[%s]:%d", ip.String(), TCPPort)
102 | }
103 | return func(ctx context.Context, network, address string) (net.Conn, error) {
104 | return (&net.Dialer{}).DialContext(ctx, network, fakeSourceAddr)
105 | }
106 | }
107 |
108 | // return download Speed
109 | func downloadHandler(ip *net.IPAddr) float64 {
110 | client := &http.Client{
111 | Transport: &http.Transport{DialContext: getDialContext(ip)},
112 | Timeout: Timeout,
113 | CheckRedirect: func(req *http.Request, via []*http.Request) error {
114 | if len(via) > 10 {
115 | return http.ErrUseLastResponse
116 | }
117 | if req.Header.Get("Referer") == defaultURL {
118 | req.Header.Del("Referer")
119 | }
120 | return nil
121 | },
122 | }
123 | req, err := http.NewRequest("GET", URL, nil)
124 | if err != nil {
125 | return 0.0
126 | }
127 |
128 | req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36")
129 |
130 | response, err := client.Do(req)
131 | if err != nil {
132 | return 0.0
133 | }
134 | defer response.Body.Close()
135 | if response.StatusCode != 200 {
136 | return 0.0
137 | }
138 | timeStart := time.Now()
139 | timeEnd := timeStart.Add(Timeout)
140 |
141 | contentLength := response.ContentLength
142 | buffer := make([]byte, bufferSize)
143 |
144 | var (
145 | contentRead int64 = 0
146 | timeSlice = Timeout / 100
147 | timeCounter = 1
148 | lastContentRead int64 = 0
149 | )
150 |
151 | var nextTime = timeStart.Add(timeSlice * time.Duration(timeCounter))
152 | e := ewma.NewMovingAverage()
153 |
154 | // Continuously calculates; if the file download is complete (both are equal), exits the loop (terminates speed testing)
155 | for contentLength != contentRead {
156 | currentTime := time.Now()
157 | if currentTime.After(nextTime) {
158 | timeCounter++
159 | nextTime = timeStart.Add(timeSlice * time.Duration(timeCounter))
160 | e.Add(float64(contentRead - lastContentRead))
161 | lastContentRead = contentRead
162 | }
163 | // If the download speed test time exceeds, exits the loop (terminates speed testing)
164 | if currentTime.After(timeEnd) {
165 | break
166 | }
167 | bufferRead, err := response.Body.Read(buffer)
168 | if err != nil {
169 | if err != io.EOF {
170 | break
171 | } else if contentLength == -1 {
172 | break
173 | }
174 | // Obtains the previous time slice
175 | last_time_slice := timeStart.Add(timeSlice * time.Duration(timeCounter-1))
176 | // Downloaded data amount / (current time - previous time slice / time slice)
177 | e.Add(float64(contentRead-lastContentRead) / (float64(currentTime.Sub(last_time_slice)) / float64(timeSlice)))
178 | }
179 | contentRead += int64(bufferRead)
180 | }
181 | return e.Value() / (Timeout.Seconds() / 120)
182 | }
183 |
--------------------------------------------------------------------------------
/utils/csv.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "encoding/csv"
5 | "fmt"
6 | "log"
7 | "net"
8 | "os"
9 | "strconv"
10 | "time"
11 | )
12 |
13 | const (
14 | defaultOutput = "result.csv"
15 | maxDelay = 9999 * time.Millisecond
16 | minDelay = 0 * time.Millisecond
17 | maxLossRate float32 = 1.0
18 | )
19 |
20 | var (
21 | InputMaxDelay = maxDelay
22 | InputMinDelay = minDelay
23 | InputMaxLossRate = maxLossRate
24 | Output = defaultOutput
25 | PrintNum = 10
26 | )
27 |
28 | // Check if to print test results
29 | func NoPrintResult() bool {
30 | return PrintNum == 0
31 | }
32 |
33 | // Check if to output to file
34 | func noOutput() bool {
35 | return Output == "" || Output == " "
36 | }
37 |
38 | type PingData struct {
39 | IP *net.IPAddr
40 | Sended int
41 | Received int
42 | Delay time.Duration
43 | }
44 |
45 | type CloudflareIPData struct {
46 | *PingData
47 | lossRate float32
48 | DownloadSpeed float64
49 | }
50 |
51 | // Calculate packet loss rate
52 | func (cf *CloudflareIPData) getLossRate() float32 {
53 | if cf.lossRate == 0 {
54 | pingLost := cf.Sended - cf.Received
55 | cf.lossRate = float32(pingLost) / float32(cf.Sended)
56 | }
57 | return cf.lossRate
58 | }
59 |
60 | func (cf *CloudflareIPData) toString() []string {
61 | result := make([]string, 6)
62 | result[0] = cf.IP.String()
63 | result[1] = strconv.Itoa(cf.Sended)
64 | result[2] = strconv.Itoa(cf.Received)
65 | result[3] = strconv.FormatFloat(float64(cf.getLossRate()), 'f', 2, 32)
66 | result[4] = strconv.FormatFloat(cf.Delay.Seconds()*1000, 'f', 2, 32)
67 | result[5] = strconv.FormatFloat(cf.DownloadSpeed/1024/1024, 'f', 2, 32)
68 | return result
69 | }
70 |
71 | func ExportCsv(data []CloudflareIPData) {
72 | if noOutput() || len(data) == 0 {
73 | return
74 | }
75 | fp, err := os.Create(Output)
76 | if err != nil {
77 | log.Fatalf("Failed to create file [%s]: %v", Output, err)
78 | return
79 | }
80 | defer fp.Close()
81 | w := csv.NewWriter(fp) // Create a new file writing stream
82 | _ = w.Write([]string{"IP Address", "Sent", "Received", "Loss Rate", "Average Delay", "Download Speed (MB/s)"})
83 | _ = w.WriteAll(convertToString(data))
84 | w.Flush()
85 | }
86 |
87 | func convertToString(data []CloudflareIPData) [][]string {
88 | result := make([][]string, 0)
89 | for _, v := range data {
90 | result = append(result, v.toString())
91 | }
92 | return result
93 | }
94 |
95 | // Delay and packet loss sorting
96 | type PingDelaySet []CloudflareIPData
97 |
98 | // Delay condition filtering
99 | func (s PingDelaySet) FilterDelay() (data PingDelaySet) {
100 | if InputMaxDelay > maxDelay || InputMinDelay < minDelay { // When the input delay condition is not within the default range, no filtering is performed
101 | return s
102 | }
103 | if InputMaxDelay == maxDelay && InputMinDelay == minDelay { // When the input delay condition is the default value, no filtering is performed
104 | return s
105 | }
106 | for _, v := range s {
107 | if v.Delay > InputMaxDelay { // Upper limit of average delay, when the delay is greater than the maximum value of the condition, no subsequent data meets the condition, directly exit the loop
108 | break
109 | }
110 | if v.Delay < InputMinDelay { // Lower limit of average delay, when the delay is less than the minimum value of the condition, it does not meet the condition, skip
111 | continue
112 | }
113 | data = append(data, v) // When the delay meets the condition, add it to the new array
114 | }
115 | return
116 | }
117 |
118 | // Packet loss condition filtering
119 | func (s PingDelaySet) FilterLossRate() (data PingDelaySet) {
120 | if InputMaxLossRate >= maxLossRate { // When the input packet loss condition is the default value, no filtering is performed
121 | return s
122 | }
123 | for _, v := range s {
124 | if v.getLossRate() > InputMaxLossRate { // Upper limit of packet loss rate
125 | break
126 | }
127 | data = append(data, v) // When the packet loss rate meets the condition, add it to the new array
128 | }
129 | return
130 | }
131 |
132 | func (s PingDelaySet) Len() int {
133 | return len(s)
134 | }
135 | func (s PingDelaySet) Less(i, j int) bool {
136 | iRate, jRate := s[i].getLossRate(), s[j].getLossRate()
137 | if iRate != jRate {
138 | return iRate < jRate
139 | }
140 | return s[i].Delay < s[j].Delay
141 | }
142 | func (s PingDelaySet) Swap(i, j int) {
143 | s[i], s[j] = s[j], s[i]
144 | }
145 |
146 | // Download speed sorting
147 | type DownloadSpeedSet []CloudflareIPData
148 |
149 | func (s DownloadSpeedSet) Len() int {
150 | return len(s)
151 | }
152 | func (s DownloadSpeedSet) Less(i, j int) bool {
153 | return s[i].DownloadSpeed > s[j].DownloadSpeed
154 | }
155 | func (s DownloadSpeedSet) Swap(i, j int) {
156 | s[i], s[j] = s[j], s[i]
157 | }
158 |
159 | func (s DownloadSpeedSet) Print() {
160 | if NoPrintResult() {
161 | return
162 | }
163 | if len(s) <= 0 { // When the length of the IP array (number of IPs) is 0, skip outputting results
164 | fmt.Println("\n[Info] The number of complete test results IP is 0, skipping output results.")
165 | return
166 | }
167 | dateString := convertToString(s) // Convert to multi-dimensional array [][]string
168 | if len(dateString) < PrintNum { // If the length of the IP array (number of IPs) is less than the printing times, change the times to the number of IPs
169 | PrintNum = len(dateString)
170 | }
171 | headFormat := "%-15s%-5s%-9s%-10s%-14s%-21s\n"
172 | dataFormat := "%-17s%-7s%-7s%-13s%-15s%-15s\n"
173 | for i := 0; i < PrintNum; i++ { // If the IPs to be output contain IPv6, adjust the spacing
174 | if len(dateString[i][0]) > 15 {
175 | headFormat = "%-40s%-5s%-9s%-10s%-14s%-21s\n"
176 | dataFormat = "%-42s%-7s%-7s%-13s%-15s%-15s\n"
177 | break
178 | }
179 | }
180 | fmt.Printf(headFormat, "IP Address", "Sent", "Received", "Loss-Rate", "Average-Delay", "Download-Speed (MB/s)")
181 | for i := 0; i < PrintNum; i++ {
182 | fmt.Printf(dataFormat, dateString[i][0], dateString[i][1], dateString[i][2], dateString[i][3], dateString[i][4], dateString[i][5])
183 | }
184 | if !noOutput() {
185 | fmt.Printf("\nComplete test results have been written to %v file, which can be viewed using Notepad/Spreadsheet software.\n", Output)
186 | }
187 | }
188 |
--------------------------------------------------------------------------------
/task/ip.go:
--------------------------------------------------------------------------------
1 | package task
2 |
3 | import (
4 | "bufio"
5 | "log"
6 | "math/rand"
7 | "net"
8 | "os"
9 | "strconv"
10 | "strings"
11 | "time"
12 | )
13 |
14 | const defaultInputFile = "ip.txt"
15 |
16 | var (
17 | // TestAll tests all IPs
18 | TestAll = false
19 | // IPFile is the filename of IP ranges
20 | IPFile = defaultInputFile
21 | IPText string
22 | )
23 |
24 | func InitRandSeed() {
25 | rand.Seed(time.Now().UnixNano())
26 | }
27 |
28 | func isIPv4(ip string) bool {
29 | return strings.Contains(ip, ".")
30 | }
31 |
32 | func randIPEndWith(num byte) byte {
33 | if num == 0 { // For single IP like /32
34 | return byte(0)
35 | }
36 | return byte(rand.Intn(int(num)))
37 | }
38 |
39 | type IPRanges struct {
40 | ips []*net.IPAddr
41 | mask string
42 | firstIP net.IP
43 | ipNet *net.IPNet
44 | }
45 |
46 | func newIPRanges() *IPRanges {
47 | return &IPRanges{
48 | ips: make([]*net.IPAddr, 0),
49 | }
50 | }
51 |
52 | // If it's a single IP, add a subnet mask, otherwise get the subnet mask (r.mask)
53 | func (r *IPRanges) fixIP(ip string) string {
54 | // If it doesn't contain '/', it's not an IP range but a single IP, so add /32 or /128 subnet mask
55 | if i := strings.IndexByte(ip, '/'); i < 0 {
56 | if isIPv4(ip) {
57 | r.mask = "/32"
58 | } else {
59 | r.mask = "/128"
60 | }
61 | ip += r.mask
62 | } else {
63 | r.mask = ip[i:]
64 | }
65 | return ip
66 | }
67 |
68 | // Parse IP range to get IP, IP range, and subnet mask
69 | func (r *IPRanges) parseCIDR(ip string) {
70 | var err error
71 | if r.firstIP, r.ipNet, err = net.ParseCIDR(r.fixIP(ip)); err != nil {
72 | log.Fatalln("ParseCIDR error", err)
73 | }
74 | }
75 |
76 | func (r *IPRanges) appendIPv4(d byte) {
77 | r.appendIP(net.IPv4(r.firstIP[12], r.firstIP[13], r.firstIP[14], d))
78 | }
79 |
80 | func (r *IPRanges) appendIP(ip net.IP) {
81 | r.ips = append(r.ips, &net.IPAddr{IP: ip})
82 | }
83 |
84 | // Get the minimum value and available number of the fourth segment of the IP
85 | func (r *IPRanges) getIPRange() (minIP, hosts byte) {
86 | minIP = r.firstIP[15] & r.ipNet.Mask[3] // Minimum value of the fourth segment of the IP
87 |
88 | // Get the number of hosts based on the subnet mask
89 | m := net.IPv4Mask(255, 255, 255, 255)
90 | for i, v := range r.ipNet.Mask {
91 | m[i] ^= v
92 | }
93 | total, _ := strconv.ParseInt(m.String(), 16, 32) // Total available IPs
94 | if total > 255 { // Correct the available IP count of the fourth segment
95 | hosts = 255
96 | return
97 | }
98 | hosts = byte(total)
99 | return
100 | }
101 |
102 | func (r *IPRanges) chooseIPv4() {
103 | if r.mask == "/32" { // Single IP, no need to randomize, just add itself
104 | r.appendIP(r.firstIP)
105 | } else {
106 | minIP, hosts := r.getIPRange() // Get the minimum value and available number of the fourth segment of the IP
107 | for r.ipNet.Contains(r.firstIP) { // Continue looping as long as the IP does not exceed the IP range
108 | if TestAll { // If testing all IPs
109 | for i := 0; i <= int(hosts); i++ { // Iterate through the last segment of the IP from the minimum value to the maximum value
110 | r.appendIPv4(byte(i) + minIP)
111 | }
112 | } else { // Randomize the last segment of the IP 0.0.0.X
113 | r.appendIPv4(minIP + randIPEndWith(hosts))
114 | }
115 | r.firstIP[14]++ // 0.0.(X+1).X
116 | if r.firstIP[14] == 0 {
117 | r.firstIP[13]++ // 0.(X+1).X.X
118 | if r.firstIP[13] == 0 {
119 | r.firstIP[12]++ // (X+1).X.X.X
120 | }
121 | }
122 | }
123 | }
124 | }
125 |
126 | func (r *IPRanges) chooseIPv6() {
127 | if r.mask == "/128" { // Single IP, no need to randomize, just add itself
128 | r.appendIP(r.firstIP)
129 | } else {
130 | var tempIP uint8 // Temporary variable to record the value of the previous bit
131 | for r.ipNet.Contains(r.firstIP) { // Continue looping as long as the IP does not exceed the IP range
132 | r.firstIP[15] = randIPEndWith(255) // Randomize the last segment of the IP
133 | r.firstIP[14] = randIPEndWith(255) // Randomize the last segment of the IP
134 |
135 | targetIP := make([]byte, len(r.firstIP))
136 | copy(targetIP, r.firstIP)
137 | r.appendIP(targetIP) // Add to the IP address pool
138 |
139 | for i := 13; i >= 0; i-- { // Randomize from the third to the first bit
140 | tempIP = r.firstIP[i] // Save the value of the previous bit
141 | r.firstIP[i] += randIPEndWith(255) // Randomize 0~255 and add it to the current bit
142 | if r.firstIP[i] >= tempIP { // If the value of the current bit is greater than or equal to the value of the previous bit, the randomization is successful and the loop can be exited
143 | break
144 | }
145 | }
146 | }
147 | }
148 | }
149 |
150 | func loadIPRanges() []*net.IPAddr {
151 | ranges := newIPRanges()
152 | if IPText != "" { // Get IP range data from the parameter
153 | IPs := strings.Split(IPText, ",") // Split by comma and iterate over the array
154 | for _, IP := range IPs {
155 | IP = strings.TrimSpace(IP) // Trim leading and trailing whitespace (spaces, tabs, newline characters, etc.)
156 | if IP == "" { // Skip empty lines (e.g., consecutive ,, at the beginning, end, or in between)
157 | continue
158 | }
159 | ranges.parseCIDR(IP) // Parse IP range to get IP, IP range, and subnet mask
160 | if isIPv4(IP) { // Generate all IPv4 / IPv6 addresses to be tested (single / random / all)
161 | ranges.chooseIPv4()
162 | } else {
163 | ranges.chooseIPv6()
164 | }
165 | }
166 | } else { // Get IP range data from the file
167 | if IPFile == "" {
168 | IPFile = defaultInputFile
169 | }
170 | file, err := os.Open(IPFile)
171 | if err != nil {
172 | log.Fatal(err)
173 | }
174 | defer file.Close()
175 | scanner := bufio.NewScanner(file)
176 | for scanner.Scan() { // Iterate over each line in the file
177 | line := strings.TrimSpace(scanner.Text()) // Trim leading and trailing whitespace (spaces, tabs, newline characters, etc.)
178 | if line == "" { // Skip empty lines
179 | continue
180 | }
181 | ranges.parseCIDR(line) // Parse IP range to get IP, IP range, and subnet mask
182 | if isIPv4(line) { // Generate all IPv4 / IPv6 addresses to be tested (single / random / all)
183 | ranges.chooseIPv4()
184 | } else {
185 | ranges.chooseIPv6()
186 | }
187 | }
188 | }
189 | return ranges.ips
190 | }
191 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "flag"
6 | "fmt"
7 | "net/http"
8 | "os"
9 | "runtime"
10 | "time"
11 |
12 | "github.com/Ptechgithub/CloudflareScanner/task"
13 | "github.com/Ptechgithub/CloudflareScanner/utils"
14 | )
15 |
16 | var (
17 | version, versionNew string
18 | )
19 |
20 | func init() {
21 | var printVersion bool
22 | var help = `
23 | CloudflareScanner ` + version + `
24 | Test the latency and speed of all IP addresses of Cloudflare CDN, and get the fastest IP (IPv4+IPv6)!
25 | https://github.com/Ptechgithub/CloudflareScanner
26 |
27 | Options:
28 | -n 200
29 | Latency test threads; more threads lead to faster latency testing, do not set too high for low-performance devices (e.g., routers); (default 200, maximum 1000)
30 | -t 4
31 | Latency test times; number of times to test latency for a single IP; (default 4 times)
32 | -dn 10
33 | Download test count; after latency testing and sorting, number of IPs to test download speed from lowest latency; (default 10)
34 | -dt 10
35 | Download test time; maximum time for download speed test of a single IP, should not be too short; (default 10 seconds)
36 | -tp 443
37 | Specify test port; port used for latency test/download test; (default port 443)
38 | -url https://speed.cloudflare.com/__down?bytes=52428800
39 | Specify test address; address used for latency test (HTTPing)/download test, default address is not guaranteed to be available, it is recommended to self-host;
40 |
41 | -httping
42 | Switch test mode; switch latency test mode to HTTP protocol, test address used is from [-url] parameter; (default TCPing)
43 | -httping-code 200
44 | Valid status code; valid HTTP status code returned during HTTPing latency test, only one is allowed; (default 200 301 302)
45 | -cfcolo HKG,KHH,NRT,LAX,SEA,SJC,FRA,MAD
46 | Match specified region; region name is local airport code, separated by English comma, only available in HTTPing mode; (default all regions)
47 |
48 | -tl 200
49 | Maximum average latency; only output IPs with latency lower than specified maximum average latency, various upper and lower limit conditions can be combined; (default 9999 ms)
50 | -tll 40
51 | Minimum average latency; only output IPs with latency higher than specified minimum average latency; (default 0 ms)
52 | -tlr 0.2
53 | Maximum loss rate; only output IPs with loss rate lower than/equal to specified loss rate, range 0.00~1.00, 0 filters out any loss IPs; (default 1.00)
54 | -sl 5
55 | Minimum download speed; only output IPs with download speed higher than specified download speed, stop testing when enough IPs are gathered [-dn]; (default 0.00 MB/s)
56 |
57 | -p 10
58 | Display result count; directly display specified number of results after testing, when 0, results are not displayed and program exits; (default 10)
59 | -f ip.txt
60 | IP range data file; if path contains spaces, please enclose in quotes; supports other CDN IP ranges; (default ip.txt)
61 | -ip 1.1.1.1,2.2.2.2/24,2606:4700::/32
62 | Specify IP range data; specify IP range data to be tested directly through parameters, separated by English comma; (default none)
63 | -o result.csv
64 | Write result file; if path contains spaces, please enclose in quotes; leave empty to not write to file [-o ""]; (default result.csv)
65 |
66 | -dd
67 | Disable download test; after disabling, test results are sorted by latency (default sorted by download speed); (default enabled)
68 | -allip
69 | Test all IPs; test each IP in IP range (IPv4 only) (default randomly test one IP in each /24 range)
70 |
71 | -v
72 | Print program version + check for updates
73 | -h
74 | Print help instructions
75 | `
76 | var minDelay, maxDelay, downloadTime int
77 | var maxLossRate float64
78 | flag.IntVar(&task.Routines, "n", 200, "Latency test threads")
79 | flag.IntVar(&task.PingTimes, "t", 4, "Latency test times")
80 | flag.IntVar(&task.TestCount, "dn", 10, "Download test count")
81 | flag.IntVar(&downloadTime, "dt", 10, "Download test time")
82 | flag.IntVar(&task.TCPPort, "tp", 443, "Specify test port")
83 | flag.StringVar(&task.URL, "url", "https://speed.cloudflare.com/__down?bytes=52428800", "Specify test address")
84 |
85 | flag.BoolVar(&task.Httping, "httping", false, "Switch test mode")
86 | flag.IntVar(&task.HttpingStatusCode, "httping-code", 0, "Valid status code")
87 | flag.StringVar(&task.HttpingCFColo, "cfcolo", "", "Match specified region")
88 |
89 | flag.IntVar(&maxDelay, "tl", 9999, "Maximum average latency")
90 | flag.IntVar(&minDelay, "tll", 0, "Minimum average latency")
91 | flag.Float64Var(&maxLossRate, "tlr", 1, "Maximum loss rate")
92 | flag.Float64Var(&task.MinSpeed, "sl", 0, "Minimum download speed")
93 |
94 | flag.IntVar(&utils.PrintNum, "p", 10, "Display result count")
95 | flag.StringVar(&task.IPFile, "f", "ip.txt", "IP range data file")
96 | flag.StringVar(&task.IPText, "ip", "", "Specify IP range data")
97 | flag.StringVar(&utils.Output, "o", "result.csv", "Output result file")
98 |
99 | flag.BoolVar(&task.Disable, "dd", false, "Disable download test")
100 | flag.BoolVar(&task.TestAll, "allip", false, "Test all IPs")
101 |
102 | flag.BoolVar(&printVersion, "v", false, "Print program version")
103 | flag.Usage = func() { fmt.Print(help) }
104 | flag.Parse()
105 |
106 | if task.MinSpeed > 0 && time.Duration(maxDelay)*time.Millisecond == utils.InputMaxDelay {
107 | fmt.Println("[Tip] When using [-sl] parameter, it is recommended to use [-tl] parameter to avoid continuous testing due to insufficient number of [-dn]...")
108 | }
109 | utils.InputMaxDelay = time.Duration(maxDelay) * time.Millisecond
110 | utils.InputMinDelay = time.Duration(minDelay) * time.Millisecond
111 | utils.InputMaxLossRate = float32(maxLossRate)
112 | task.Timeout = time.Duration(downloadTime) * time.Second
113 | task.HttpingCFColomap = task.MapColoMap()
114 |
115 | if printVersion {
116 | println(version)
117 | fmt.Println("Checking for updates...")
118 | checkUpdate()
119 | if versionNew != "" {
120 | fmt.Printf("*** Found new version [%s]! Please go to [https://github.com/Ptechgithub/CloudflareScanner] to update! ***", versionNew)
121 | } else {
122 | fmt.Println("Current version is the latest [" + version + "]!")
123 | }
124 | os.Exit(0)
125 | }
126 | }
127 |
128 | func main() {
129 | task.InitRandSeed() // Set random seed
130 |
131 | fmt.Printf("# Ptechgithub/CloudflareScanner %s \n\n", version)
132 |
133 | // Start latency testing + filter delay/loss
134 | pingData := task.NewPing().Run().FilterDelay().FilterLossRate()
135 | // Start download speed testing
136 | speedData := task.TestDownloadSpeed(pingData)
137 | utils.ExportCsv(speedData) // Export to file
138 | speedData.Print() // Print results
139 |
140 | if versionNew != "" {
141 | fmt.Printf("\n*** Found New Version [%s]! Please go to [https://github.com/Ptechgithub/CloudflareScanner] to update! ***\n", versionNew)
142 | }
143 | endPrint()
144 | }
145 |
146 | func endPrint() {
147 | if utils.NoPrintResult() {
148 | return
149 | }
150 | if runtime.GOOS == "windows" { // If Windows, need to press Enter or Ctrl+C to exit (avoids closing after completion when run by double-clicking)
151 | fmt.Printf("Press Enter or Ctrl+C to exit.")
152 | fmt.Scanln()
153 | }
154 | }
155 |
156 | // Check for updates
157 | func checkUpdate() {
158 | timeout := 10 * time.Second
159 | client := http.Client{Timeout: timeout}
160 | res, err := client.Get("https://api.github.com/repos/Ptechgithub/CloudflareScanner/releases/latest")
161 | if err != nil {
162 | return
163 | }
164 | defer res.Body.Close()
165 |
166 | var release struct {
167 | TagName string `json:"tag_name"`
168 | }
169 | err = json.NewDecoder(res.Body).Decode(&release)
170 | if err != nil {
171 | return
172 | }
173 |
174 | if release.TagName != version {
175 | versionNew = release.TagName
176 | }
177 | }
178 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Ptechgithub/CloudflareScanner
2 |
3 | [](https://github.com/Ptechgithub/CloudflareScanner/)[](https://github.com/Ptechgithub/CloudflareScanner/releases/latest)[](https://github.com/Ptechgithub/CloudflareScanner/)[](https://github.com/Ptechgithub/CloudflareScanner/)[](https://github.com/Ptechgithub/CloudflareScanner/)
4 |
5 | Many foreign websites are using Cloudflare CDN, but the IP assigned to visitors from mainland China is not friendly (high latency, high packet loss, and slow speed).
6 | While Cloudflare exposes all [IP segment](https://www.cloudflare.com/ips/), but trying to find one that suits you among so many IPs would be exhausting, so I came up with this software.
7 |
8 | **"Self-selected preferred IP" tests Cloudflare CDN latency and speed to obtain the fastest IP (IPv4+IPv6) **! If it's useful**Click`⭐`Give me some encouragement~**
9 |
10 | * * *
11 |
12 | ### Quick to use
13 |
14 | ### Download and run
15 |
16 | 1. Download the compiled executable file [Github Releases](https://github.com/Ptechgithub/CloudflareScanner/releases) and unzip it.
17 | 2. Double click to run`CloudflareScanner.exe`File (Windows system), waiting for the speed test to complete...
18 |
19 |
20 | 「 Click to view usage examples on Linux system 」
21 |
22 | * * *
23 |
24 | The following commands are only examples. For the version number and file name, please go to [**Releases**](https://github.com/Ptechgithub/CloudflareScanner/releases) Check.
25 |
26 | ```yaml
27 | # If this is your first time using it, it is recommended to create a new folder (skip this step for subsequent updates)
28 | mkdir CloudflareScanner
29 |
30 | # Enter the folder (for subsequent updates, only repeat the following download and unzip commands from here)
31 | cd CloudflareScanner
32 |
33 | # Download the CloudflareScanner zip file (replace [version number] and [file name] in the URL according to your needs)
34 | wget -N https://github.com/Ptechgithub/CloudflareScanner/releases/download/v2.2.5/CloudflareScanner_linux_amd64.zip
35 | # If you are downloading in a Chinese network environment, please use one of the following mirror accelerations:
36 | # wget -N https://download.scholar.rr.nu/Ptechgithub/CloudflareScanner/releases/download/v2.2.5/CloudflareScanner_linux_amd64.zip
37 | # wget -N https://ghproxy.cc/https://github.com/Ptechgithub/CloudflareScanner/releases/download/v2.2.5/CloudflareScanner_linux_amd64.zip
38 | # wget -N https://ghproxy.net/https://github.com/Ptechgithub/CloudflareScanner/releases/download/v2.2.5/CloudflareScanner_linux_amd64.zip
39 | # wget -N https://gh-proxy.com/https://github.com/Ptechgithub/CloudflareScanner/releases/download/v2.2.5/CloudflareScanner_linux_amd64.zip
40 | # wget -N https://mirror.ghproxy.com/https://github.com/Ptechgithub/CloudflareScanner/releases/download/v2.2.5/CloudflareScanner_linux_amd64.zip
41 | # If the download fails, try removing the -N parameter (if for updating, remember to delete the old zip file in advance rm CloudflareScanner_linux_amd64.zip)
42 |
43 | # Unzip (no need to delete old files, they will be overwritten directly, replace the file name according to your needs)
44 | tar -zxf CloudflareScanner_linux_amd64.zip
45 |
46 | # Grant execution permission
47 | chmod +x CloudflareScanner
48 |
49 | # Run (without parameters)
50 | ./CloudflareScanner
51 |
52 | # Run (with parameter example)
53 | ./CloudflareScanner -dd -tll 90
54 | ```
55 |
56 | > If flat**Very low latency**(such as 0.xx), then CloudflareScanner**The agent left during the speed test**, please close the proxy software before testing the speed.
57 | > if in**router**It is recommended to turn off the proxy in the router first (or exclude it), otherwise the speed test results may be**Inaccurate/unusable**。
58 |
59 |
60 |
61 | * * *
62 | > Notice! This software only works on websites,**Preferred IP for Cloudflare WARP is not supported**, see for details:[#392](https://github.com/Ptechgithub/CloudflareScanner/discussions/392)
63 |
64 | ### Example of results
65 |
66 | After the speed test is completed, it will be displayed by default**Fastest 10 IPs**, example:
67 |
68 | ```bash
69 | IP Address Sent Received Loss-Rate Avg-Latency Download Speed (MB/s)
70 | 104.27.200.69 4 4 0.00 146.23 28.64
71 | 172.67.60.78 4 4 0.00 139.82 15.02
72 | 104.25.140.153 4 4 0.00 146.49 14.90
73 | 104.27.192.65 4 4 0.00 140.28 14.07
74 | 172.67.62.214 4 4 0.00 139.29 12.71
75 | 104.27.207.5 4 4 0.00 145.92 11.95
76 | 172.67.54.193 4 4 0.00 146.71 11.55
77 | 104.22.66.8 4 4 0.00 147.42 11.11
78 | 104.27.197.63 4 4 0.00 131.29 10.26
79 | 172.67.58.91 4 4 0.00 140.19 9.14
80 | ...
81 |
82 | # If the average latency is very low (e.g., 0.xx), it indicates that CloudflareScanner is using a proxy during the speed test. Please disable any proxy software before conducting the test.
83 | # If running on a router, please disable any proxies within the router (or exclude them), otherwise the speed test results may be inaccurate/unusable.
84 |
85 | # Because each speed test randomly selects an IP from each IP range, the results will vary each time, which is normal!
86 |
87 | # Note! I found that after the computer boots up, the first speed test may have noticeably higher latency (manual TCPing is the same), but subsequent tests are normal.
88 | # Therefore, it is recommended that before conducting the first official speed test after booting up, randomly test a few IPs (no need to wait for the latency test to complete, just close it once the progress bar moves).
89 |
90 | # The entire process of the software under the default parameters:
91 | # 1. Latency test (default TCPing mode, HTTPing mode requires manual addition of parameters)
92 | # 2. Latency sorting (sorting latency from low to high and filtering according to conditions, different loss rates are sorted separately, so there may be some IPs with low latency but loss at the end)
93 | # 3. Download speed test (starting from the IP with the lowest latency, downloading speed tests one by one, the default stops after testing 10)
94 | # 4. Speed sorting (sorting speeds from high to low)
95 | # 5. Output results (control whether to output to the command line with parameters (-p 0) or output to a file (-o ""))
96 |
97 | # Note: The result file result.csv will display Chinese garbled characters when opened with Microsoft Excel, which is normal. It displays normally in other spreadsheet software/notepad.
98 | ```
99 |
100 | The first line of the speed test result is**The fastest IP with the fastest download speed and lowest average latency**!
101 |
102 | The complete results are saved in the current directory`result.csv`file, use**Notepad/sheet software**Open, the format is as follows:
103 |
104 | IP Address, Sent, Received, Loss Rate, Average Latency, Download Speed (MB/s)
105 | 104.27.200.69,4,4,0.00,146.23,28.64
106 |
107 | > _You can view the complete results according to your own needs**Further filtering**, or take a look at the advanced usage**Specify filter criteria**!_
108 |
109 | * * *
110 |
111 | ### Advanced use
112 |
113 | The default parameters are used for direct operation. If you want the speed measurement results to be more comprehensive and more in line with your own requirements, you can customize the parameters.
114 |
115 | ```css
116 | C:\>CloudflareScanner.exe -h
117 |
118 | CloudflareScanner vX.X.X
119 | Test the latency and speed of all IP addresses of Cloudflare CDN to obtain the fastest IP (IPv4+IPv6)!
120 | https://github.com/Ptechgithub/CloudflareScanner
121 |
122 | Options:
123 | -n 200
124 | Latency test threads; more threads result in faster latency testing, but devices with weak performance (such as routers) should not set it too high; (default 200, maximum 1000)
125 | -t 4
126 | Latency test count; number of times each IP's latency is tested; (default 4 times)
127 | -dn 10
128 | Download test count; number of IPs to download speed test after latency testing and sorting, starting from the lowest latency; (default 10)
129 | -dt 10
130 | Download test time; maximum download test time for each IP, should not be too short; (default 10 seconds)
131 | -tp 443
132 | Specify test port; port used for latency testing/download testing; (default port 443)
133 | -url https://cf.xiu2.xyz/url
134 | Specify test URL; URL used for latency testing (HTTPing)/download testing, default URL not guaranteed to be available, it is recommended to use a self-built one;
135 |
136 | -httping
137 | Switch test mode; switch latency test mode to HTTP protocol, using the test address specified by [-url] parameter; (default TCPing)
138 | Note: HTTPing is essentially a form of network scanning behavior, so if you are running it on a server, you need to reduce concurrency (-n), otherwise some strict merchants may suspend service.
139 | If you encounter a situation where the number of IPs available for HTTPing latency testing is normal at first, but decreases in subsequent tests or even becomes 0, but then recovers after a while, it may also be due to temporary restrictions triggered by the ISP or Cloudflare CDN due to network scanning behavior, it is recommended to reduce concurrency (-n) to reduce the occurrence of such situations.
140 | -httping-code 200
141 | Valid status codes; valid HTTP status codes returned when latency testing with HTTPing, limited to one; (default 200 301 302)
142 | -cfcolo HKG,KHH,NRT,LAX,SEA,SJC,FRA,MAD
143 | Match specified locations; location names are three-letter airport codes, separated by commas, case-insensitive, supports Cloudflare, AWS CloudFront, only available in HTTPing mode; (default all locations)
144 |
145 | -tl 200
146 | Upper limit of average latency; only output IPs with latency lower than the specified value, upper and lower limit conditions can be used together; (default 9999 ms)
147 | -tll 40
148 | Lower limit of average latency; only output IPs with latency higher than the specified value; (default 0 ms)
149 | -tlr 0.2
150 | Upper limit of loss rate; only output IPs with loss rate lower than/equal to the specified value, range 0.00~1.00, 0 filters out any IPs with loss; (default 1.00)
151 | -sl 5
152 | Lower limit of download speed; only output IPs with download speed higher than the specified value, will stop testing when the specified number [-dn] is reached; (default 0.00 MB/s)
153 |
154 | -p 10
155 | Number of results to display; directly display the specified number of results after testing, when set to 0, results will not be displayed and the program will exit directly; (default 10)
156 | -f ip.txt
157 | IP range data file; if the path contains spaces, please enclose it in quotes; supports other CDN IP ranges; (default ip.txt)
158 | -ip 1.1.1.1,2.2.2.2/24,2606:4700::/32
159 | Specify IP range data; directly specify the IP range data to be tested through parameters, separated by commas; (default empty)
160 | -o result.csv
161 | Write result to file; if the path contains spaces, please enclose it in quotes; set to empty [-o ""] to not write to file; (default result.csv)
162 |
163 | -dd
164 | Disable download speed test; after disabling, the test results will be sorted by latency (default sorted by download speed); (default enabled)
165 | -allip
166 | Test all IPs; test each IP in the IP range (IPv4 only); (default randomly test one IP from each /24 range)
167 |
168 | -v
169 | Print program version + check for updates
170 | -h
171 | Print help information
172 | ```
173 |
174 | ### Interface explanation
175 |
176 | In order to prevent everyone from being concerned about the speed measurement process,**The output content is misunderstood (available, queue and other numbers, the download speed test is "interrupted" halfway?)**, I explain specifically.
177 |
178 |
179 | 「 Click to expand view content 」
180 |
181 | * * *
182 |
183 | > This example adds all common parameters, which is:`-ttl 40 -tl 150 -sl 1 -dn 5`, the final output result is as follows:
184 |
185 | ```bash
186 | # Ptechgithub/CloudflareScanner vX.X.X
187 |
188 | Starting latency test (mode: TCP, port: 443, range: 40 ~ 150 ms, loss: 1.00)
189 | 321 / 321 [----------------------------------------------------------------------------------] Available: 30
190 | Starting download speed test (minimum: 1.00 MB/s, count: 5, queue: 10)
191 | 3 / 5 [---------------------------------------------------------↗---------------------------]
192 | IP Address Sent Received Loss Rate Avg Latency Download Speed (MB/s)
193 | XXX.XXX.XXX.XXX 4 4 0.00 83.32 3.66
194 | XXX.XXX.XXX.XXX 4 4 0.00 107.81 2.49
195 | XXX.XXX.XXX.XXX 4 3 0.25 149.59 1.04
196 |
197 | Full test results have been written to the result.csv file, which can be viewed using Notepad/spreadsheet software.
198 | Press Enter or Ctrl+C to exit.
199 | ```
200 |
201 | * * *
202 |
203 | > People who are new to CloudflareScanner may be confused**There are obviously 30 IPs available for delay speed testing, so why are there only 3 left in the end?**
204 | > What does the queue in the download speed test mean? Do I still have to queue up when I download the speed test?
205 |
206 | CloudflareScanner will first delay the speed test, during which the number of available IPs will be displayed in real time on the right side of the progress bar (`Available: 30`), but note that the available quantity refers to**Number of IPs that passed the test without timeout**, has nothing to do with the upper and lower limits of delay and packet loss conditions. When the delayed speed test is completed, because it is also specified**Delay upper and lower limits, packet loss**conditions, so after filtering according to the conditions, only`10`Already (that is, waiting for the download speed test)`queue:10`)。
207 |
208 | That is, in the above example,`321`After the IP delay speed test is completed, only`30`Each IP test passes without timeout, and then according to the upper and lower limit range of delay:`40 ~ 150 ms`and packet loss upper limit conditions, only`10`There is an IP that meets the requirements. if you`-dd`If the download speed test is disabled, this will be output directly.`10`IP. Of course, this example is not disabled, so the software will continue to`10`IP for download speed test (`queue:10`)。
209 |
210 | > Because the download speed test is a single-threaded one-by-one IP queue test, so the number of IPs waiting for the download speed test is called`queue`。
211 |
212 | * * *
213 |
214 | > You may have noticed,**It was clearly designated to find 5 IPs that meet the download speed conditions, but why was it "interrupted" after only 3?**
215 |
216 | Download speed test progress bar`3 / 5`, the former refers to finding`3`IPs that meet the lower limit of download speed (that is, the download speed is higher than`1 MB/s`),the latter`5`Refers to your request to find`5`IPs that meet the lower limit of download speed (`-dn 5`)。
217 |
218 | > Also, a reminder, if you specify`-dn`is larger than the download speed test queue. For example, after you delay the speed test, only`4`IP, then the numbers behind the download speed test progress bar will be the same as the download speed test queue.`4`one, not you`-dn`Specified`5`Already.
219 |
220 | The software is finishing the speed test`10`After IPs, only`3`download speeds higher than`1 MB/s`of IPs, and the rest`7`Each IP is "failed".
221 |
222 | Therefore, this is not "Every time the speed test falls short of 5 it interrupts", but rather, all IPs have been downloaded and their speeds tested, yet only found `3` that meet the criteria.
223 |
224 | * * *
225 |
226 | If you don’t want to encounter this situation where few of the speed tests meet the conditions, then you have to**Lower the download speed limit parameter`-sl`**, or remove.
227 |
228 | Because as long as you specify`-sl`parameters, then as long as there are not enough`-dn`number (default 10), the speed test will continue until enough or all speed tests are completed. Remove`-sl`and add`-dn 20`parameters, so that only the top 20 IPs with the lowest speed and delay are measured, and the speed measurement is stopped to save time.
229 |
230 | * * *
231 |
232 | In addition, if all queue IPs have been tested for speed, but there is no IP that meets the download speed conditions, then it will**Directly output the download speed test results of all queue IPs**, so that you can see the download speeds of these IPs, and you can know them in your mind, and then**Adjust it appropriately`-sl`try again**。
233 |
234 | Similarly, in terms of delayed speed measurement,`Available: 30`、`queue:10`These two values can also let you know whether the delay conditions you set are too harsh for you. If there are a lot of available IPs, but only 2 or 3 are left after conditional filtering, it goes without saying that you need**Adjust down expected latency/packet loss conditions**.
235 |
236 | Of these two mechanisms, one tells you**Delayed packet loss conditions**Whether it is appropriate or not, one will tell you**Download speed conditions**Is it appropriate.
237 |
238 |
239 |
240 | * * *
241 |
242 | ### Usage example
243 |
244 | Windows To specify parameters you need to run in CMD, or add parameters to the shortcut target.
245 |
246 | > **Notice**: Each parameter has**default value**, parameters using default values can be omitted (**Choose as needed**),parameter**In no particular order**。
247 | > **hint**:Windows**PowerShell**Just put in the following command`CloudflareScanner.exe`Change to`.\CloudflareScanner.exe`That’s it.
248 | > **hint**: Linux system only needs to change the following command`CloudflareScanner.exe`Change to`./CloudflareScanner`That’s it.
249 |
250 | * * *
251 |
252 | #### #CMD runs CloudflareScanner with parameters
253 |
254 | People who are not familiar with command line programs may not know how to run them with parameters, so I will briefly explain.
255 |
256 |
257 | 「 Click to expand view content 」
258 |
259 | * * *
260 |
261 | Many people open CMD to**absolute path**Running CloudflareScanner will report an error. This is because the default`-f ip.txt`The parameter is a relative path, and you need to specify the absolute path of ip.txt. However, this is too troublesome, so it is recommended to enter the CloudflareScanner program directory to**relative path**Run as:
262 |
263 | **method one**:
264 |
265 | 1. Open the directory where the CloudflareScanner program is located
266 | 2. Press on blank spaceShift + right mouse buttonShow right-click menu
267 | 3. choose**\[Open command window here]**to open the CMD window, which will be located in the current directory by default.
268 | 4. Enter a command with parameters, such as:`CloudflareScanner.exe -tll 50 -tl 200`Ready to run
269 |
270 | **Method 2**:
271 |
272 | 1. Open the directory where the CloudflareScanner program is located
273 | 2. Select all directly in the folder address bar and enter`cmd`Press Enter to open the CMD window, which will be in the current directory by default.
274 | 3. Enter a command with parameters, such as:`CloudflareScanner.exe -tll 50 -tl 200`Ready to run
275 |
276 | > Of course, you can also open a CMD window at will and enter such as`cd /d "D:\Program Files\CloudflareScanner"`to enter the program directory
277 |
278 | > **hint**: If using**PowerShell**Just put in the command`CloudflareScanner.exe`Change to`.\CloudflareScanner.exe`That’s it.
279 |
280 |
281 |
282 | * * *
283 |
284 | #### #Windows shortcut to run CloudflareScanner with parameters
285 |
286 | If you don’t frequently modify the running parameters (for example, you usually just double-click to run), it is recommended to use the shortcut, which is more convenient.
287 |
288 |
289 | 「 Click to expand view content 」
290 |
291 | * * *
292 |
293 | Right click`CloudflareScanner.exe`document -**\[Create Shortcut]**, then right-click the shortcut -**\[Attributes]**, modify its**Target**:
294 |
295 | ```bash
296 | # If you don't want to output the result file, please add -o " ", where the quotes contain a space (omitting the space will cause this parameter to be omitted).
297 | D:\ABC\CloudflareScanner\CloudflareScanner.exe -n 500 -t 4 -dn 20 -dt 5 -o " "
298 |
299 | # If the file path contains quotes, then the startup parameters need to be placed outside the quotes, make sure there is a space between the quotes and -.
300 | "D:\Program Files\CloudflareScanner\CloudflareScanner.exe" -n 500 -t 4 -dn 20 -dt 5 -o " "
301 |
302 | # Note! The starting position of the shortcut - cannot be empty, otherwise the ip.txt file will not be found due to the absolute path.
303 | ```
304 |
305 |
306 |
307 | * * *
308 |
309 | #### IPv4/IPv6
310 |
311 |
312 | 「 Click to expand view content 」
313 |
314 | * * *
315 |
316 | ```bash
317 | # You can specify the built-in IPv4 data file to test these IPv4 addresses (-f default value is ip.txt, so this parameter can be omitted)
318 | CloudflareScanner.exe -f ip.txt
319 |
320 | # You can specify the built-in IPv6 data file to test these IPv6 addresses
321 | # Additionally, starting from version 2.1.0, CloudflareScanner supports mixed IPv4+IPv6 speed testing and removes the -ipv6 parameter, so one file can contain both IPv4+IPv6 addresses.
322 | CloudflareScanner.exe -f ipv6.txt
323 |
324 | # You can also directly specify the IP addresses to be tested through parameters
325 | CloudflareScanner.exe -ip 1.1.1.1,2606:4700::/32
326 | ```
327 |
328 | > When measuring IPv6 speed, you may notice that the number of speed measurements is different each time. Learn the reason:[#120](https://github.com/Ptechgithub/CloudflareScanner/issues/120)
329 | > Because there are too many IPv6s (in billions), and most of the IP segments are not enabled at all, I only scanned some of the available IPv6 segments and wrote`ipv6.txt`In the file, those who are interested can scan for additions and deletions by themselves. The ASN data source comes from:[bgp.he.net](https://bgp.he.net/AS13335#_prefixes6)
330 |
331 |
332 |
333 | * * *
334 |
335 | #### #HTTPing
336 |
337 |
338 | 「 Click to expand view content 」
339 |
340 | * * *
341 |
342 | There are currently two delayed speed measurement modes, namely**TCP protocol, HTTP protocol**。
343 | The TCP protocol takes less time, consumes less resources, and has a timeout of 1 second. This protocol is the default mode.
344 | The HTTP protocol is suitable for quickly testing whether a domain name is accessible when pointing to a certain IP. The timeout is 2 seconds.
345 | For the same IP, the delay obtained by pinging various protocols is generally:**ICMP < TCP < HTTP**, the further to the right, the more sensitive it is to network fluctuations such as packet loss.
346 |
347 | > Note: HTTPing is essentially a**Network scan**behavior, so if you are running on a server, you need**Reduce concurrency**(`-n`), otherwise the service may be suspended by some strict merchants. If you encounter a situation where the number of available IPs in the first HTTPing speed test is normal, and subsequent speed tests are getting less and less or even directly to 0, but then recover after stopping for a period of time, it may be because the operator or Cloudflare CDN thinks you are scanning the network.**Trigger temporary restriction mechanism**, so it will recover after a while, it is recommended**Reduce concurrency**(`-n`) to reduce the occurrence of this situation.
348 |
349 | > In addition, this software HTTPing only obtains**response headers**, and does not obtain the body content (that is, the URL file size does not affect the HTTPing test, but if you want to download the speed test, you still need a large file), similar to the curl -i function.
350 |
351 | ```bash
352 | # Simply add the -httping parameter to switch to HTTP protocol latency testing mode
353 | CloudflareScanner.exe -httping
354 |
355 | # The software will determine availability based on the valid HTTP status codes returned when accessing the webpage (of course, timeouts also count). By default, 200, 301, and 302 are considered valid HTTP status codes. You can manually specify valid HTTP status codes, but only one can be specified (you need to determine in advance which status code the test address will return under normal circumstances).
356 | CloudflareScanner.exe -httping -httping-code 200
357 |
358 | # Specify the HTTPing test address through the -url parameter (can be any webpage URL, not limited to specific file addresses)
359 | CloudflareScanner.exe -httping -url https://cf.xiu2.xyz/url
360 | # If you want to HTTPing test other websites/CDNs, specify an address used by that website/CDN (because the software's default address is Cloudflare's, it can only be used to test Cloudflare's IPs)
361 |
362 | # Note: If the test address is using HTTP protocol, remember to add -tp 80 (this parameter will affect the port used during latency testing/download testing)
363 | # Similarly, if you want to test port 80, you also need to add the -url parameter to specify an address using the http:// protocol (and this address will not be forcibly redirected to HTTPS). If it is a non-80 or 443 port, make sure the download test address supports access through that port.
364 | ```
365 |
366 |
367 |
368 | * * *
369 |
370 | #### #Match the specified area (colo airport three-character code)
371 |
372 |
373 | 「 Click to expand view content 」
374 |
375 | * * *
376 |
377 | ```bash
378 | # This feature supports both Cloudflare CDN and AWS CloudFront CDN, and the three-letter airport codes for these two CDNs are interchangeable.
379 | # Note: If you want to use it to filter AWS CloudFront CDN regions, you need to specify an address using that CDN through the -url parameter (because the default address of the software is Cloudflare's).
380 |
381 | # After specifying the region name, the results obtained after latency testing will all be IPs from the specified region (you can also continue to perform download speed tests).
382 | # Node region names are three-letter airport codes, separated by commas when specifying multiple, lowercase letters are supported starting from version 2.2.3.
383 |
384 | CloudflareScanner.exe -cfcolo HKG,KHH,NRT,LAX,SEA,SJC,FRA,MAD
385 |
386 | # Note that this parameter is only available in HTTPing latency testing mode (because it requires accessing web pages to obtain).
387 | ```
388 |
389 | > The two CDN airport three-character codes are common, so each region name is visible:
390 |
391 |
392 |
393 | * * *
394 |
395 | #### File relative/absolute path
396 |
397 |
398 | 「 Click to expand view content 」
399 |
400 | * * *
401 |
402 | ```bash
403 | # Specify IPv4 data file, do not display results and exit directly, output results to file (-p value is 0)
404 | CloudflareScanner.exe -f 1.txt -p 0 -dd
405 |
406 | # Specify IPv4 data file, do not output results to file, display results directly (-p value is 10, -o value is empty but quotes cannot be omitted)
407 | CloudflareScanner.exe -f 2.txt -o "" -p 10 -dd
408 |
409 | # Specify IPv4 data file and output results to file (relative path, i.e., in the current directory, if it contains spaces, please enclose it in quotes)
410 | CloudflareScanner.exe -f 3.txt -o result.txt -dd
411 |
412 |
413 | # Specify IPv4 data file and output results to file (relative path, i.e., in the abc folder in the current directory, if it contains spaces, please enclose it in quotes)
414 | # Linux (in the abc folder within the CloudflareScanner program directory)
415 | ./CloudflareScanner -f abc/3.txt -o abc/result.txt -dd
416 |
417 | # Windows (note the backslash)
418 | CloudflareScanner.exe -f abc\3.txt -o abc\result.txt -dd
419 |
420 |
421 | # Specify IPv4 data file and output results to file (absolute path, i.e., in the C:\abc\ directory, if it contains spaces, please enclose it in quotes)
422 | # Linux (in the /abc/ directory)
423 | ./CloudflareScanner -f /abc/4.txt -o /abc/result.csv -dd
424 |
425 | # Windows (note the backslash)
426 | CloudflareScanner.exe -f C:\abc\4.txt -o C:\abc\result.csv -dd
427 |
428 |
429 | # If you want to run CloudflareScanner with an absolute path, then the filenames in the -f / -o parameters must also be absolute paths, otherwise an error will occur indicating that the file cannot be found!
430 | # Linux (in the /abc/ directory)
431 | /abc/CloudflareScanner -f /abc/4.txt -o /abc/result.csv -dd
432 |
433 | # Windows (note the backslash)
434 | C:\abc\CloudflareScanner.exe -f C:\abc\4.txt -o C:\abc\result.csv -dd
435 | ```
436 |
437 |
438 |
439 | * * *
440 |
441 | #### #Test speed of other ports
442 |
443 |
444 | 「 Click to expand view content 」
445 |
446 | * * *
447 |
448 | ```bash
449 | # If you want to test ports other than the default 443, you need to specify them through the -tp parameter (this parameter will affect the port used during latency testing/download testing).
450 |
451 | # If you want to latency test port 80 + download speed (if -dd disables download speed testing, it is not necessary), then you also need to specify an http:// protocol download speed test address (and this address will not be forcibly redirected to HTTPS, because that would become port 443).
452 | CloudflareScanner.exe -tp 80 -url http://cdn.cloudflare.steamstatic.com/steam/apps/5952/movie_max.webm
453 |
454 | # If it is a port other than 80 or 443, you need to make sure that the download test address you are using supports access through that non-standard port.
455 | ```
456 |
457 |
458 |
459 | * * *
460 |
461 | #### #Custom speed test address
462 |
463 |
464 | 「 Click to expand view content 」
465 |
466 | * * *
467 |
468 | ```bash
469 | # This parameter is applicable to download speed testing and HTTP protocol latency testing, for the latter, the address can be any webpage URL (not limited to specific file addresses).
470 |
471 | # Address requirements: directly downloadable, file size exceeds 200MB, using Cloudflare CDN
472 | CloudflareScanner.exe -url https://cf.xiu2.xyz/url
473 |
474 | # Note: If the test address is using the HTTP protocol (this address cannot be forcibly redirected to HTTPS), remember to add -tp 80 (this parameter will affect the port used during latency testing/download testing). If it is a non-80 or 443 port, make sure the download test address supports access through that port.
475 | CloudflareScanner.exe -tp 80 -url http://cdn.cloudflare.steamstatic.com/steam/apps/5952/movie_max.webm
476 | ```
477 |
478 |
479 |
480 | * * *
481 |
482 | #### #Custom speed test conditions (specify the target range of latency/packet loss/download speed)
483 |
484 |
485 | 「 Click to expand view content 」
486 |
487 | * * *
488 |
489 | > Note: The delay speed test progress bar on the right**Quantity Available**, only refers to the delayed speed measurement process**Number of IPs that have not timed out**, regardless of the delay upper and lower bound conditions.
490 |
491 | - Specify only**[Average latency cap]**condition
492 |
493 | ```bash
494 | # Maximum average latency: 200 ms, minimum download speed: 0 MB/s
495 | # In other words, find IPs with an average latency below 200 ms, and then perform 10 download speed tests in order of increasing latency.
496 | CloudflareScanner.exe -tl 200
497 | ```
498 |
499 | > if**No satisfying delay found**conditional IP, nothing will be output.
500 |
501 | * * *
502 |
503 | - Specify only**[Average latency cap]**conditions, and**Only delay the speed test, do not download the speed test**
504 |
505 | ```bash
506 | # Maximum average latency: 200 ms, minimum download speed: 0 MB/s, quantity: unknown
507 | # In other words, only output IPs with an average latency below 200 ms, and no longer perform download speed tests (because download speed tests are no longer performed, the -dn parameter becomes ineffective).
508 | CloudflareScanner.exe -tl 200 -dd
509 | ```
510 |
511 | - Specify only**[Maximum packet loss probability]**condition
512 |
513 | ```bash
514 | # Maximum loss rate: 0.25
515 | # In other words, find IPs with a loss rate lower than or equal to 0.25, range 0.00~1.00. If -tlr 0, it means filtering out any IPs with loss.
516 | CloudflareScanner.exe -tlr 0.25
517 | ```
518 |
519 | * * *
520 |
521 | - Specify only**[Download speed minimum]**condition
522 |
523 | ```bash
524 | # Maximum average latency: 9999 ms, minimum download speed: 5 MB/s, quantity: 10 (optional)
525 | # In other words, it needs to find 10 IPs with an average latency below 9999 ms and a download speed higher than 5 MB/s to stop the speed test.
526 | CloudflareScanner.exe -sl 5 -dn 10
527 | ```
528 |
529 | > if**Didn't find one that met the speed**conditional IP, then it will**Ignore conditions and output all IP speed test results**(This will help you adjust the conditions next time you test your speed).
530 |
531 | > When the upper limit of average delay is not specified, if it has been**Not enough**The number of IPs that meet the conditions will**Always measuring speed**Go down.
532 | > So it is recommended**Specify at the same time[Download speed minimum]+[Average latency cap]**, so that the speed test will be terminated before the specified delay upper limit is reached before sufficient numbers are collected.
533 |
534 | * * *
535 |
536 | - Specify at the same time**[Average latency cap]+[Download speed minimum]**condition
537 |
538 | ```bash
539 | # Maximum average latency and minimum download speed support decimals (e.g., -sl 0.5)
540 | # Maximum average latency: 200 ms, minimum download speed: 5.6 MB/s, quantity: 10 (optional)
541 | # In other words, it needs to find 10 IPs with an average latency below 200 ms and a download speed higher than 5.6 MB/s to stop the speed test.
542 | CloudflareScanner.exe -tl 200 -sl 5.6 -dn 10
543 | ```
544 |
545 | > if**No satisfying delay found**conditional IP, nothing will be output.
546 | > if**Didn't find one that met the speed**IP of the condition, then all IP speed test results will be output regardless of the condition (convenient for you to adjust the conditions the next time you test the speed).
547 | > Therefore, it is recommended to test the speed without specifying conditions first to see what the average delay and download speed are, and avoid specifying conditions.**too low/too high**!
548 |
549 | > Because the IP range exposed by Cloudflare is**Back-to-origin IP + Anycast IP**,and**Back to source IP**is unavailable, so the download speed test is 0.00.
550 | > You can add it at runtime`-sl 0.01`(lower limit of download speed), filter out**Back to source IP**(Results of download speed test below 0.01MB/s).
551 |
552 |
553 |
554 | * * *
555 |
556 | #### Test the speed of one or multiple IPs individually
557 |
558 |
559 | 「 Click to expand view content 」
560 |
561 | * * *
562 |
563 | **method one**:
564 | Directly specify the IP segment data to be measured through parameters.
565 |
566 | ```bash
567 | # First navigate to the directory where CloudflareScanner is located, then run:
568 | # For Windows systems (run in CMD)
569 | CloudflareScanner.exe -ip 1.1.1.1,2.2.2.2/24,2606:4700::/32
570 |
571 | # For Linux systems
572 | ./CloudflareScanner -ip 1.1.1.1,2.2.2.2/24,2606:4700::/32
573 | ```
574 |
575 | * * *
576 |
577 | **Method 2**:
578 | Or write these IPs into any text file in the following format, for example:`1.txt`
579 |
580 | 1.1.1.1
581 | 1.1.1.200
582 | 1.0.0.1/24
583 | 2606:4700::/32
584 |
585 | > You can omit it for a single IP`/32`subnet masked (i.e.`1.1.1.1`Equivalent to`1.1.1.1/32`)。
586 | > subnet mask`/24`Refers to the last segment of this IP, that is`1.0.0.1~1.0.0.255`。
587 |
588 | Then add startup parameters when running CloudflareScanner`-f 1.txt`to specify the IP segment data file.
589 |
590 | ```bash
591 | # First navigate to the directory where CloudflareScanner is located, then run:
592 | # For Windows systems (run in CMD)
593 | CloudflareScanner.exe -f 1.txt
594 |
595 | # For Linux systems
596 | ./CloudflareScanner -f 1.txt
597 |
598 | # For IP ranges like 1.0.0.1/24, only the last segment (1.0.0.1~255) will be randomly selected. If you want to test all IPs in that range, please add the -allip parameter.
599 | ```
600 |
601 |
602 |
603 | * * *
604 |
605 | ## Manual compilation
606 |
607 |
608 | 「 Click to expand view content 」
609 |
610 | * * *
611 |
612 | For convenience, I write the version number into the version variable in the code when compiling, so when you compile manually, you need to add it as follows:`go build`Add after the command`-ldflags`Parameter to specify the version number:
613 |
614 | ```bash
615 | # Run this command in the CloudflareScanner directory via the command line (e.g., CMD, Bat script) to compile a binary executable program that can run in an environment with the same system, bitness, and architecture as the current device (Go will automatically detect your system bitness and architecture), and the version number will be v2.2.5.
616 |
617 | go build -ldflags "-s -w -X main.version=v2.2.5"
618 | ```
619 |
620 | If you want to compile under Windows 64-bit system**Other systems, architectures, bits**, then you need to specify**GOOS**and**GOARCH**variable.
621 |
622 | For example, under Windows system, compile a program suitable for**Linux system amd architecture 64 bit**Binary program for:
623 |
624 | ```bat
625 | SET GOOS=linux
626 | SET GOARCH=amd64
627 | go build -ldflags "-s -w -X main.version=v2.2.5"
628 | ```
629 |
630 | For example, under Linux system, compile a program suitable for**Windows system amd architecture 32 bit**Binary program for:
631 |
632 | ```bash
633 | GOOS=windows
634 | GOARCH=386
635 | go build -ldflags "-s -w -X main.version=v2.2.5"
636 | ```
637 |
638 | > Can run`go tool dist list`to see which combinations the current Go version supports compiling.
639 |
640 | * * *
641 |
642 | Of course, in order to facilitate batch compilation, I will specifically specify a variable as the version number, and subsequent compilations can directly call the version number variable.
643 | At the same time, if you want to compile in batches, you need to put them in different folders (or the file names are different). You need to add`-o`Parameters specified.
644 |
645 | ```bat
646 | :: For Windows system:
647 | SET version=v2.2.5
648 | SET GOOS=linux
649 | SET GOARCH=amd64
650 | go build -o Releases\CloudflareScanner_linux_amd64\CloudflareScanner -ldflags "-s -w -X main.version=%version%"
651 | ```
652 |
653 | ```bash
654 | # For Linux system:
655 | version=v2.2.5
656 | GOOS=windows
657 | GOARCH=386
658 | go build -o Releases/CloudflareScanner_windows_386/CloudflareScanner.exe -ldflags "-s -w -X main.version=${version}"
659 | ```
660 |
661 |
662 |
663 | * * *
664 |
665 | ## License
666 |
667 | The GPL-3.0 License.
668 |
--------------------------------------------------------------------------------