├── .gitattributes
├── .github
└── ISSUE_TEMPLATE
│ ├── 01-bugReport.yml
│ ├── 02-featureRequest.yml
│ └── config.yml
├── .gitignore
├── LICENSE
├── README.md
├── go.mod
├── go.sum
├── ip.txt
├── ipv6.txt
├── main.go
├── script
├── README.md
├── cfst_3proxy.bat
├── cfst_ddns.bat
├── cfst_ddns.sh
├── cfst_dnsmasq.sh
├── cfst_dnspod.sh
├── cfst_hosts.bat
├── cfst_hosts.sh
└── cfst_hosts_mac.sh
├── task
├── download.go
├── httping.go
├── ip.go
└── tcping.go
└── utils
├── csv.go
└── progress.go
/.gitattributes:
--------------------------------------------------------------------------------
1 | script/*.* linguist-language=None
2 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/01-bugReport.yml:
--------------------------------------------------------------------------------
1 | name: 反馈问题 (Bug report)
2 | description: 软件报错等异常情况,或遇到预期之外的问题...
3 | labels: 反馈问题
4 | body:
5 | - type: markdown
6 | attributes:
7 | value: |
8 | 发之前,请先搜下有没有类似的 [**Issues**](https://github.com/XIU2/CloudflareSpeedTest/issues)、[**Discussions**](https://github.com/XIU2/CloudflareSpeedTest/discussions) 问题(包括[**已关闭**](https://github.com/XIU2/CloudflareSpeedTest/issues?q=is%3Aissue+is%3Aclosed)的),请勿重复发起!
9 |
10 | > [!NOTE]
11 | > 注意!如果你反馈的问题和 CloudflareST **软件本身功能无关**(如关于 Cloudflare CDN 的网络问题),请**前往讨论区** (💬 [**Discussions**](https://github.com/XIU2/CloudflareSpeedTest/discussions)) 发帖交流!(不合适的 Issues 会被转过去
12 | ****
13 | - type: textarea
14 | id: description
15 | attributes:
16 | label: 问题描述
17 | description: 必填,最好写上 复现问题 的步骤,越详细越好,特别是一些复杂的问题
18 | placeholder: 请输入...
19 | validations:
20 | required: true
21 | - type: input
22 | id: version
23 | attributes:
24 | label: 软件版本
25 | description: 必填,可通过运行软件来获取版本信息(例如 v2.2.2)
26 | placeholder: 请输入...
27 | validations:
28 | required: true
29 | - type: textarea
30 | id: screenshots
31 | attributes:
32 | label: 附加截图
33 | description: 可选,也可以是一些错误代码
34 | placeholder: 可在此粘贴图片,或点击下方 [Attach files by dragging & dropping, selecting or pasting them.] 文字来选择图片...
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/02-featureRequest.yml:
--------------------------------------------------------------------------------
1 | name: 功能建议 (Feature request)
2 | description: 有什么建议,或希望添加、完善某个功能...
3 | labels: 功能建议
4 | body:
5 | - type: markdown
6 | attributes:
7 | value: |
8 | 发之前,请先搜下有没有类似的 [**Issues**](https://github.com/XIU2/CloudflareSpeedTest/issues)、[**Discussions**](https://github.com/XIU2/CloudflareSpeedTest/discussions) 问题(包括[**已关闭**](https://github.com/XIU2/CloudflareSpeedTest/issues?q=is%3Aissue+is%3Aclosed)的),请勿重复发起!
9 |
10 | > [!NOTE]
11 | > 注意!如果你提的功能建议和 CloudflareST **软件本身功能无关**,请**前往讨论区** (💬 [**Discussions**](https://github.com/XIU2/CloudflareSpeedTest/discussions)) 发帖交流!
12 |
13 | > [!TIP]
14 | > 另外,不接受**个性化**的小众功能请求(即 **很少人** 或 **只有你自己** 才会用到的功能)
15 | ****
16 | - type: textarea
17 | id: description
18 | attributes:
19 | label: 功能需求
20 | description: 必填,你要什么样的功能?
21 | placeholder: 请输入...
22 | validations:
23 | required: true
24 | - type: textarea
25 | id: anticipation
26 | attributes:
27 | label: 预期目标
28 | description: 必填,你希望该功能具体是什么样子的?如果能提供 示例/截图/代码 就更好了
29 | placeholder: 请输入...
30 | validations:
31 | required: true
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/config.yml:
--------------------------------------------------------------------------------
1 | blank_issues_enabled: false
2 | contact_links:
3 | - name: 前往讨论区 (💬 Discussions)
4 | url: https://github.com/XIU2/CloudflareSpeedTest/discussions
5 | about: Issues 仅用于对 CloudflareST 本身的反馈问题、功能建议,其他话题请到 💬 Discussions 发帖讨论(不合适的 Issues 会被转过去
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | dist
2 | Releases
3 | *.exe
4 | *.csv
5 |
--------------------------------------------------------------------------------
/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 | # XIU2/CloudflareSpeedTest
2 |
3 | [](https://github.com/XIU2/CloudflareSpeedTest/)
4 | [](https://github.com/XIU2/CloudflareSpeedTest/releases/latest)
5 | [](https://github.com/XIU2/CloudflareSpeedTest/)
6 | [](https://github.com/XIU2/CloudflareSpeedTest/)
7 | [](https://github.com/XIU2/CloudflareSpeedTest/)
8 |
9 | 国外很多网站都在使用 Cloudflare CDN,但分配给中国内地访客的 IP 并不友好(延迟高、丢包多、速度慢)。
10 | 虽然 Cloudflare 公开了所有 [IP 段](https://www.cloudflare.com/zh-cn/ips/) ,但想要在这么多 IP 中找到适合自己的,怕是要累死,于是就有了这个软件。
11 |
12 | **「自选优选 IP」测试 Cloudflare CDN 延迟和速度,获取最快 IP (IPv4+IPv6)**!好用的话**点个`⭐`鼓励一下叭~**
13 |
14 | > _分享我其他开源项目:[**TrackersList.com** - 全网热门 BT Tracker 列表!有效提高 BT 下载速度~](https://github.com/XIU2/TrackersListCollection)
_
15 | > _[**UserScript** - 🐵 Github 高速下载、知乎增强、自动无缝翻页、护眼模式 等十几个**油猴脚本**~](https://github.com/XIU2/UserScript)
_
16 | > _[**SNIProxy** - 🧷 自用的简单 SNI Proxy(支持全平台、全系统、前置代理、配置简单等~](https://github.com/XIU2/SNIProxy)
_
17 |
18 | > 本项目也支持对**其他 CDN / 网站 IP** 延迟测速(如:[CloudFront](https://github.com/XIU2/CloudflareSpeedTest/discussions/304)、[Gcore](https://github.com/XIU2/CloudflareSpeedTest/discussions/303) CDN),但下载测速需自行寻找地址
19 |
20 | > [!IMPORTANT]
21 | > Cloudflare CDN 已**明文禁止代理**方式使用,对于**代理套 CDN** 的自行承担风险,请勿过度依赖 [#382](https://github.com/XIU2/CloudflareSpeedTest/discussions/382) [#383](https://github.com/XIU2/CloudflareSpeedTest/discussions/383)
22 |
23 | ****
24 | ## \# 快速使用
25 |
26 | ### 下载运行
27 |
28 | 1. 下载编译好的可执行文件( [Github Releases](https://github.com/XIU2/CloudflareSpeedTest/releases) / [蓝奏云](https://pan.lanpw.com/b0742hkxe) )并解压。
29 | 2. 双击运行 `CloudflareST.exe` 文件(Windows 系统),等待测速完成...
30 |
31 |
32 | 「 点击查看 Windows 系统下其他安装方式」
33 |
34 | ****
35 |
36 | 通过scoop安装:
37 | ```sh
38 | # 添加最多人使用的中文软件包仓库:dorado
39 | scoop bucket add dorado https://github.com/chawyehsu/dorado
40 | # 安装cloudflare-speedtest
41 | scoop install dorado/cloudflare-speedtest
42 | ```
43 |
44 |
45 |
46 |
47 | 「 点击查看 Linux 系统下的使用示例 」
48 |
49 | ****
50 |
51 | 以下命令仅为示例,版本号和文件名请前往 [**Releases**](https://github.com/XIU2/CloudflareSpeedTest/releases) 查看。
52 |
53 | ``` yaml
54 | # 如果是第一次使用,则建议创建新文件夹(后续更新时,跳过该步骤)
55 | mkdir CloudflareST
56 |
57 | # 进入文件夹(后续更新,只需要从这里重复下面的下载、解压命令即可)
58 | cd CloudflareST
59 |
60 | # 下载 CloudflareST 压缩包(自行根据需求替换 URL 中 [版本号] 和 [文件名])
61 | wget -N https://github.com/XIU2/CloudflareSpeedTest/releases/download/v2.2.5/CloudflareST_linux_amd64.tar.gz
62 | # 如果你是在国内网络环境中下载,那么请使用下面这几个镜像加速之一:
63 | # wget -N https://ghp.ci/https://github.com/XIU2/CloudflareSpeedTest/releases/download/v2.2.5/CloudflareST_linux_amd64.tar.gz
64 | # wget -N https://ghproxy.cc/https://github.com/XIU2/CloudflareSpeedTest/releases/download/v2.2.5/CloudflareST_linux_amd64.tar.gz
65 | # wget -N https://ghproxy.net/https://github.com/XIU2/CloudflareSpeedTest/releases/download/v2.2.5/CloudflareST_linux_amd64.tar.gz
66 | # wget -N https://gh-proxy.com/https://github.com/XIU2/CloudflareSpeedTest/releases/download/v2.2.5/CloudflareST_linux_amd64.tar.gz
67 | # 如果下载失败的话,尝试删除 -N 参数(如果是为了更新,则记得提前删除旧压缩包 rm CloudflareST_linux_amd64.tar.gz )
68 |
69 | # 解压(不需要删除旧文件,会直接覆盖,自行根据需求替换 文件名)
70 | tar -zxf CloudflareST_linux_amd64.tar.gz
71 |
72 | # 赋予执行权限
73 | chmod +x CloudflareST
74 |
75 | # 运行(不带参数)
76 | ./CloudflareST
77 |
78 | # 运行(带参数示例)
79 | ./CloudflareST -dd -tll 90
80 | ```
81 |
82 | > 如果平**均延迟非常低**(如 0.xx),则说明 CloudflareST **测速时走了代理**,请先关闭代理软件后再测速。
83 | > 如果在**路由器**上运行,建议先关闭路由器内的代理(或将其排除),否则测速结果可能会**不准确/无法使用**。
84 |
85 |
86 |
87 | ****
88 |
89 | > _在**手机**上独立运行 CloudflareST 测速的简单教程:**[Android](https://github.com/XIU2/CloudflareSpeedTest/discussions/61)、[Android APP](https://github.com/xianshenglu/cloudflare-ip-tester-app)、[IOS](https://github.com/XIU2/CloudflareSpeedTest/discussions/321)**_
90 |
91 | > [!NOTE]
92 | > 注意!本软件仅适用于网站,**不支持给使用 UDP 协议的 Cloudflare WARP 优选 IP**,具体见:[#392](https://github.com/XIU2/CloudflareSpeedTest/discussions/392)
93 |
94 | ### 结果示例
95 |
96 | 测速完毕后,默认会显示**最快的 10 个 IP**,示例:
97 |
98 | ``` bash
99 | IP 地址 已发送 已接收 丢包率 平均延迟 下载速度 (MB/s)
100 | 104.27.200.69 4 4 0.00 146.23 28.64
101 | 172.67.60.78 4 4 0.00 139.82 15.02
102 | 104.25.140.153 4 4 0.00 146.49 14.90
103 | 104.27.192.65 4 4 0.00 140.28 14.07
104 | 172.67.62.214 4 4 0.00 139.29 12.71
105 | 104.27.207.5 4 4 0.00 145.92 11.95
106 | 172.67.54.193 4 4 0.00 146.71 11.55
107 | 104.22.66.8 4 4 0.00 147.42 11.11
108 | 104.27.197.63 4 4 0.00 131.29 10.26
109 | 172.67.58.91 4 4 0.00 140.19 9.14
110 | ...
111 |
112 | # 如果平均延迟非常低(如 0.xx),则说明 CloudflareST 测速时走了代理,请先关闭代理软件后再测速。
113 | # 如果在路由器上运行,请先关闭路由器内的代理(或将其排除),否则测速结果可能会不准确/无法使用。
114 |
115 | # 因为每次测速都是在每个 IP 段中随机 IP,所以每次的测速结果都不可能相同,这是正常的!
116 |
117 | # 注意!我发现电脑开机后第一次测速延迟会明显偏高(手动 TCPing 也一样),后续测速都正常
118 | # 因此建议大家开机后第一次正式测速前,先随便测几个 IP(无需等待延迟测速完成,只要进度条动了就可以直接关了)
119 |
120 | # 软件在 默认参数 下的整个流程大概步骤:
121 | # 1. 延迟测速(默认 TCPing 模式,HTTPing 模式需要手动加上参数)
122 | # 2. 延迟排序(延迟 从低到高 排序并按条件过滤,不同丢包率会分开排序,因此可能会有一些延迟低但丢包的 IP 排到后面)
123 | # 3. 下载测速(从延迟最低的 IP 开始依次下载测速,默认测够 10 个就会停止)
124 | # 4. 速度排序(速度从高到低排序)
125 | # 5. 输出结果(通过参数控制是否输出到命令行(-p 0)或输出到文件(-o ""))
126 |
127 | # 注意:输出的结果文件 result.csv 通过微软 Excel 表格打开会中文乱码,这是正常的,其他表格软件/记事本都显示正常
128 | ```
129 |
130 | 测速结果第一行就是**既下载速度最快、又平均延迟最低的最快 IP**!
131 |
132 | 完整结果保存在当前目录下的 `result.csv` 文件中,用**记事本/表格软件**打开,格式如下:
133 |
134 | ```
135 | IP 地址,已发送,已接收,丢包率,平均延迟,下载速度 (MB/s)
136 | 104.27.200.69,4,4,0.00,146.23,28.64
137 | ```
138 |
139 | > _大家可以按自己需求,对完整结果**进一步筛选处理**,或者去看一看进阶使用**指定过滤条件**!_
140 |
141 | ****
142 | ## \# 进阶使用
143 |
144 | 直接运行使用的是默认参数,如果想要测速结果更全面、更符合自己的要求,可以自定义参数。
145 |
146 | ```Dart
147 | C:\>CloudflareST.exe -h
148 |
149 | CloudflareSpeedTest vX.X.X
150 | 测试 Cloudflare CDN 所有 IP 的延迟和速度,获取最快 IP (IPv4+IPv6)!
151 | https://github.com/XIU2/CloudflareSpeedTest
152 |
153 | 参数:
154 | -n 200
155 | 延迟测速线程;越多延迟测速越快,性能弱的设备 (如路由器) 请勿太高;(默认 200 最多 1000)
156 | -t 4
157 | 延迟测速次数;单个 IP 延迟测速的次数;(默认 4 次)
158 | -dn 10
159 | 下载测速数量;延迟测速并排序后,从最低延迟起下载测速的数量;(默认 10 个)
160 | -dt 10
161 | 下载测速时间;单个 IP 下载测速最长时间,不能太短;(默认 10 秒)
162 | -tp 443
163 | 指定测速端口;延迟测速/下载测速时使用的端口;(默认 443 端口)
164 | -url https://cf.xiu2.xyz/url
165 | 指定测速地址;延迟测速(HTTPing)/下载测速时使用的地址,默认地址不保证可用性,建议自建;
166 |
167 | -httping
168 | 切换测速模式;延迟测速模式改为 HTTP 协议,所用测试地址为 [-url] 参数;(默认 TCPing)
169 | 注意:HTTPing 本质上也算一种 网络扫描 行为,因此如果你在服务器上面运行,需要降低并发(-n),否则可能会被一些严格的商家暂停服务。
170 | 如果你遇到 HTTPing 首次测速可用 IP 数量正常,后续测速越来越少甚至直接为 0,但停一段时间后又恢复了的情况,那么也可能是被 运营商、Cloudflare CDN 认为你在网络扫描而 触发临时限制机制,因此才会过一会儿就恢复了,建议降低并发(-n)减少这种情况的发生。
171 | -httping-code 200
172 | 有效状态代码;HTTPing 延迟测速时网页返回的有效 HTTP 状态码,仅限一个;(默认 200 301 302)
173 | -cfcolo HKG,KHH,NRT,LAX,SEA,SJC,FRA,MAD
174 | 匹配指定地区;地区名为当地机场三字码,英文逗号分隔,支持小写,支持 Cloudflare、AWS CloudFront,仅 HTTPing 模式可用;(默认 所有地区)
175 |
176 | -tl 200
177 | 平均延迟上限;只输出低于指定平均延迟的 IP,各上下限条件可搭配使用;(默认 9999 ms)
178 | -tll 40
179 | 平均延迟下限;只输出高于指定平均延迟的 IP;(默认 0 ms)
180 | -tlr 0.2
181 | 丢包几率上限;只输出低于/等于指定丢包率的 IP,范围 0.00~1.00,0 过滤掉任何丢包的 IP;(默认 1.00)
182 | -sl 5
183 | 下载速度下限;只输出高于指定下载速度的 IP,凑够指定数量 [-dn] 才会停止测速;(默认 0.00 MB/s)
184 |
185 | -p 10
186 | 显示结果数量;测速后直接显示指定数量的结果,为 0 时不显示结果直接退出;(默认 10 个)
187 | -f ip.txt
188 | IP段数据文件;如路径含有空格请加上引号;支持其他 CDN IP段;(默认 ip.txt)
189 | -ip 1.1.1.1,2.2.2.2/24,2606:4700::/32
190 | 指定IP段数据;直接通过参数指定要测速的 IP 段数据,英文逗号分隔;(默认 空)
191 | -o result.csv
192 | 写入结果文件;如路径含有空格请加上引号;值为空时不写入文件 [-o ""];(默认 result.csv)
193 |
194 | -dd
195 | 禁用下载测速;禁用后测速结果会按延迟排序 (默认按下载速度排序);(默认 启用)
196 | -allip
197 | 测速全部的IP;对 IP 段中的每个 IP (仅支持 IPv4) 进行测速;(默认 每个 /24 段随机测速一个 IP)
198 |
199 | -v
200 | 打印程序版本 + 检查版本更新
201 | -h
202 | 打印帮助说明
203 | ```
204 |
205 | ### 界面解释
206 |
207 | 为了避免大家对测速过程中的**输出内容产生误解(可用、队列等数字,下载测速一半就"中断"?下载测速"卡住"不动?)**,我特意解释下。
208 |
209 |
210 | 「 点击展开 查看内容 」
211 |
212 | ****
213 |
214 | > 该示例把常用参数都给加上了,即为:`-tll 40 -tl 150 -sl 1 -dn 5`,最后输出结果如下:
215 |
216 | ```python
217 | # XIU2/CloudflareSpeedTest vX.X.X
218 |
219 | 开始延迟测速(模式:TCP, 端口:443, 范围:40 ~ 150 ms, 丢包:1.00)
220 | 321 / 321 [-----------------------------------------------------------] 可用: 30
221 | 开始下载测速(下限:1.00 MB/s, 数量:5, 队列:10)
222 | 3 / 5 [-----------------------------------------↗--------------------]
223 | IP 地址 已发送 已接收 丢包率 平均延迟 下载速度 (MB/s)
224 | XXX.XXX.XXX.XXX 4 4 0.00 83.32 3.66
225 | XXX.XXX.XXX.XXX 4 4 0.00 107.81 2.49
226 | XXX.XXX.XXX.XXX 4 3 0.25 149.59 1.04
227 |
228 | 完整测速结果已写入 result.csv 文件,可使用记事本/表格软件查看。
229 | 按下 回车键 或 Ctrl+C 退出。
230 | ```
231 |
232 | ****
233 |
234 | > 刚接触 CloudflareST 的人,可能会迷惑**明明延迟测速可用 IP 有 30 个,怎么最后只剩下 3 个了呢?**
235 | > 下载测速里的队列又是什么意思?难道我下载测速还要排队?
236 |
237 | CloudflareST 会先延迟测速,在这过程中进度条右侧会实时显示可用 IP 数量(`可用: 30`),但注意该可用数量指的是**测试通过没有超时的 IP 数量**,和延迟上下限、丢包条件无关。当延迟测速完成后,因为还指定了**延迟上下限、丢包**的条件,所以按照条件过滤后只剩下 `10` 个了(也就是等待下载测速的 `队列:10`)。
238 |
239 | 即以上示例中,`321` 个 IP 延迟测速完成后,只有 `30` 个 IP 测试通过没有超时,然后根据延迟上下限范围:`40 ~ 150 ms` 及丢包上限条件过滤后,只剩下 `10` 个满足要求的 IP 了。如果你 `-dd` 禁用了下载测速,那么就会直接输出这 `10` 个 IP 了。当然该示例并未禁用,因此接下来软件会继续对这 `10` 个 IP 进行下载测速(`队列:10`)。
240 |
241 | > 因为下载测速是单线程一个个 IP 挨着排队测速的,因此等待下载测速的 IP 数量才会叫做 `队列`。
242 |
243 | ****
244 |
245 | > 你可能注意到了,**明明指定了要找到 5 个满足下载速度条件的 IP,怎么才 3 个就 “中断” 了呢?**
246 |
247 | 下载测速进度条中的 `3 / 5`,前者指的是找到了 `3` 个满足下载速度下限条件的 IP(即下载速度高于 `1 MB/s` ),后者 `5` 指的是你要求找到 `5` 个满足下载速度下限条件的 IP(`-dn 5`)。
248 |
249 | > 另外,提醒一下,如果你指定的 `-dn` 大于下载测速队列,比如你延迟测速后只剩下 `4` 个 IP 了,那么下载测速进度条中后面的数字就会和下载测速队列一样都是 `4` 个,而非你 `-dn` 指定的 `5` 个了。
250 |
251 | 软件在测速完这 `10` 个 IP 后,只找到了 `3` 个下载速度高于 `1 MB/s` 的 IP,剩下的 `7` 个 IP 都是 “不及格” 的。
252 |
253 | 因此,这不是 `“每次测速都不到 5 就中断了”`,而是所有 IP 都下载测速完了,但却只找到了 `3` 个满足条件的。
254 |
255 | ****
256 |
257 | 还有一种情况,那就是当可用 IP 很多时(几百几千),你还设置了下载速度条件,那么可能就会遇到:**怎么下载测速进度条老是卡在 `X / 5` 了呢?**
258 |
259 | 这其实并不是卡住了,而是只有当找到一个满足条件的 IP 时,进度条才会 +1,因此如果一直找不到,那么 CloudflareST 就会一直下载测速下去,因此在表现为进度条卡住不动,但这也是在提醒你:你设置的下载速度条件对你来说已经高于实际了,你需要适当调低预期。
260 |
261 | ****
262 |
263 | 如果不想遇到这种全部测速一遍都没几个满足条件的情况,那么就要**调低下载速度上限参数 `-sl`**,或者移除。
264 |
265 | 因为只要指定了 `-sl` 参数,那么只要没有凑够 `-dn` 的数量(默认 10 个),就会一直测速下去,直到凑够或全部测速完。移除 `-sl` 并添加 `-dn 20` 参数,这样就是只测速延迟最低的前 20 个 IP,测速完就停止,节省时间。
266 |
267 | ****
268 |
269 | 另外,如果全部队列 IP 都测速完了,但一个满足下载速度条件的 IP 都没有,那么就会**直接输出全部队列 IP 的下载测速结果**,这样你就能看到这些 IP 的下载速度都有多少,心里也就有数了,然后**适当调低 `-sl` 再试试**。
270 |
271 | 同样,延迟测速方面,`可用: 30`、`队列:10` 这两个数值也可以让你清楚,你设置的延迟条件对你来说是否过于苛刻。如果可用 IP 一大堆,但条件过滤后只剩下 2、3 个,那不用说就知道需要**调低预期的延迟/丢包条件**了。
272 |
273 | 这两个机制,一个是告诉你**延迟丢包条件**是否合适的,一个是告诉你**下载速度条件**是否合适的。
274 |
275 |
276 |
277 | ****
278 |
279 | ### 使用示例
280 |
281 | Windows 要指定参数需要在 CMD 中运行,或者把参数添加到快捷方式目标中。
282 |
283 | > [!TIP]
284 | > - 各参数均有**默认值**,使用默认值的参数是可以省略的(**按需选择**),参数**不分前后顺序**。
285 | > - Windows **PowerShell** 只需把下面命令中的 `CloudflareST.exe` 改为 `.\CloudflareST.exe` 即可。
286 | > - Linux 系统只需要把下面命令中的 `CloudflareST.exe` 改为 `./CloudflareST` 即可。
287 |
288 | ****
289 |
290 | #### \# CMD 带参数运行 CloudflareST
291 |
292 | 对命令行程序不熟悉的人,可能不知道该如何带参数运行,我就简单说一下。
293 |
294 |
295 | 「 点击展开 查看内容 」
296 |
297 | ****
298 |
299 | 很多人打开 CMD 以**绝对路径**运行 CloudflareST 会报错,这是因为默认的 `-f ip.txt` 参数是相对路径,需要指定绝对路径的 ip.txt 才行,但这样毕竟太麻烦了,因此还是建议进入 CloudflareST 程序目录下,以**相对路径**方式运行:
300 |
301 | **方式 一**:
302 | 1. 打开 CloudflareST 程序所在目录
303 | 2. 空白处按下 Shift + 鼠标右键 显示右键菜单
304 | 3. 选择 **\[在此处打开命令窗口\]** 来打开 CMD 窗口,此时默认就位于当前目录下
305 | 4. 输入带参数的命令,如:`CloudflareST.exe -tll 50 -tl 200`即可运行
306 |
307 | **方式 二**:
308 | 1. 打开 CloudflareST 程序所在目录
309 | 2. 直接在文件夹地址栏中全选并输入 `cmd` 回车来打开 CMD 窗口,此时默认就位于当前目录下
310 | 4. 输入带参数的命令,如:`CloudflareST.exe -tll 50 -tl 200`即可运行
311 |
312 | > 当然你也可以随便打开一个 CMD 窗口,然后输入如 `cd /d "D:\Program Files\CloudflareST"` 来进入程序目录
313 |
314 | > **提示**:如果用的是 **PowerShell** 只需把命令中的 `CloudflareST.exe` 改为 `.\CloudflareST.exe` 即可。
315 |
316 |
317 |
318 | ****
319 |
320 | #### \# Windows 快捷方式带参数运行 CloudflareST
321 |
322 | 如果不经常修改运行参数(比如平时都是直接双击运行)的人,建议使用快捷方式,更方便点。
323 |
324 |
325 | 「 点击展开 查看内容 」
326 |
327 | ****
328 |
329 | 右键 `CloudflareST.exe` 文件 - **\[创建快捷方式\]**,然后右键该快捷方式 - **\[属性\]**,修改其**目标**:
330 |
331 | ``` bash
332 | # 如果要不输出结果文件,那么请加上 -o " ",引号里的是空格(没有空格会导致该参数被省略)。
333 | D:\ABC\CloudflareST\CloudflareST.exe -n 500 -t 4 -dn 20 -dt 5 -o " "
334 |
335 | # 如果文件路径包含引号,则需要把启动参数放在引号外面,记得引号和 - 之间有空格。
336 | "D:\Program Files\CloudflareST\CloudflareST.exe" -n 500 -t 4 -dn 20 -dt 5 -o " "
337 |
338 | # 注意!快捷方式 - 起始位置 不能是空的,否则就会因为绝对路径而找不到 ip.txt 文件
339 | ```
340 |
341 |
342 |
343 | ****
344 |
345 | #### \# IPv4/IPv6
346 |
347 |
348 | 「 点击展开 查看内容 」
349 |
350 | ****
351 | ``` bash
352 | # 指定自带的 IPv4 数据文件可测速这些 IPv4 地址(-f 默认值就是 ip.txt,所以该参数可省略)
353 | CloudflareST.exe -f ip.txt
354 |
355 | # 指定自带的 IPv6 数据文件可测速这些 IPv6 地址
356 | # 另外,v2.1.0 版本后支持 IPv4+IPv6 混合测速并移除了 -ipv6 参数,因此一个文件内可以同时包含 IPv4+IPv6 地址
357 | CloudflareST.exe -f ipv6.txt
358 |
359 | # 也可以直接通过参数指定要测速的 IP
360 | CloudflareST.exe -ip 1.1.1.1,2606:4700::/32
361 | ```
362 |
363 | > 测速 IPv6 时,可能会注意到每次测速数量都不一样,了解原因: [#120](https://github.com/XIU2/CloudflareSpeedTest/issues/120)
364 | > 因为 IPv6 太多(以亿为单位),且绝大部分 IP 段压根未启用,所以我只扫了一部分可用的 IPv6 段写到 `ipv6.txt` 文件中,有兴趣的可以自行扫描增删,ASN 数据源来自:[bgp.he.net](https://bgp.he.net/AS13335#_prefixes6)
365 |
366 |
367 |
368 | ****
369 |
370 | #### \# HTTPing
371 |
372 |
373 | 「 点击展开 查看内容 」
374 |
375 | ****
376 |
377 | 目前有两种延迟测速模式,分别为 **TCP 协议、HTTP 协议**。
378 | TCP 协议耗时更短、消耗资源更少,超时时间为 1 秒,该协议为默认模式。
379 | HTTP 协议适用于快速测试某域名指向某 IP 时是否可以访问,超时时间为 2 秒。
380 | 同一个 IP,各协议去 Ping 得到的延迟一般为:**ICMP < TCP < HTTP**,越靠右对丢包等网络波动越敏感。
381 |
382 | > 注意:HTTPing 本质上也算一种**网络扫描**行为,因此如果你在服务器上面运行,需要**降低并发**(`-n`),否则可能会被一些严格的商家暂停服务。如果你遇到 HTTPing 首次测速可用 IP 数量正常,后续测速越来越少甚至直接为 0,但停一段时间后又恢复了的情况,那么也可能是被 运营商、Cloudflare CDN 认为你在网络扫描而**触发临时限制机制**,因此才会过一会儿就恢复了,建议**降低并发**(`-n`)减少这种情况的发生。
383 |
384 | > 另外,本软件 HTTPing 仅获取**响应头(response headers)**,并不获取正文内容(即 URL 文件大小不影响 HTTPing 测试,但如果你还要下载测速的话,那么还是需要一个大文件的),类似于 curl -i 功能。
385 |
386 | ``` bash
387 | # 只需加上 -httping 参数即可切换到 HTTP 协议延迟测速模式
388 | CloudflareST.exe -httping
389 |
390 | # 软件会根据访问时网页返回的有效 HTTP 状态码来判断可用性(当然超时也算),默认对返回 200 301 302 这三个 HTTP 状态码的视为有效,可以手动指定认为有效的 HTTP 状态码,但只能指定一个(你需要提前确定测试地址正常情况下会返回哪个状态码)
391 | CloudflareST.exe -httping -httping-code 200
392 |
393 | # 通过 -url 参数来指定 HTTPing 测试地址(可以是任意网页 URL,不局限于具体文件地址)
394 | CloudflareST.exe -httping -url https://cf.xiu2.xyz/url
395 | # 如果你要 HTTPing 测试其他网站/CDN,那么指定一个该网站/使用该 CDN 的地址(因为软件默认地址是 Cloudflare 的,只能用于测试 Cloudflare 的 IP)
396 |
397 | # 注意:如果测速地址为 HTTP 协议,记得加上 -tp 80(这个参数会影响 延迟测速/下载测速 时使用的端口)
398 | # 同理,如果要测速 80 端口,那么也需要加上 -url 参数来指定一个 http:// 协议的地址才行(且该地址不会强制重定向至 HTTPS),如果是非 80 443 端口,那么需要确定该下载测速地址是否支持通过该端口访问。
399 | CloudflareST.exe -httping -tp 80 -url http://cdn.cloudflare.steamstatic.com/steam/apps/5952/movie_max.webm
400 | ```
401 |
402 |
403 |
404 | ****
405 |
406 | #### \# 匹配指定地区(colo 机场三字码)
407 |
408 |
409 | 「 点击展开 查看内容 」
410 |
411 | ****
412 |
413 | Cloudflare CDN 的节点 IP 是 Anycast IP,即每个 IP 对应的服务器节点及地区不是固定的,而是动态变化的,**不同地区、不同运营商、不同时间段**访问**同一个 IP** 分配到的服务器节点地区和路线也都是不一样的(比如同一个 IP,美国人访问就是分配到就近的美国节点服务器,日本人访问则就又变成了就近的日本节点服务器了,国内内地就比较特殊了,只能给你分配到其他国家,当然不同的 IP 段路由变化/分配逻辑也是不同的,有的 IP 段会较为固定)。
414 |
415 | > **注意**!虽然 Cloudflare CDN 有很多亚洲节点,但**不代表你就能用上**,新加坡人测速可能随便一抓一大把的新加坡节点,但你全部扫一遍可能都遇不到一个,因为这是由 CDN 控制的。Anycast IP 的路由是经常变的,同一个 IP 今天可能是美国,明天你再访问可能就又分配到欧洲节点了(当然这只是个例子,一般没有那么频繁,这也和很多因素有关,比如线路拥塞程度,成本变动等),因此**不要对该功能有过高期待**~
416 |
417 | 或者你随便找个 Cloudflare CDN 的 IP(比如官网域名的解析 IP `104.16.123.96`),然后去那些有全球节点的[在线 Ping 测试](https://ping.sx/ping?t=104.16.123.96)网站,你就会发现这个 IP 在全球大部分地区的延迟都是个位数(而且很多都是 0.X ms),就算一些地方延迟高一些但也基本都控制在 几十ms,只有在国内才会发现突然变成了 上百ms 了。
418 |
419 | 这就是 Anycast 技术,也就只有国内大陆这种特殊的网络情况,才需要对 Anycast 的 CDN IP 进行优选。
420 |
421 | 因此,对于这种 Anycast IP 的实际服务器位置,就不能靠那些在线 IP 地址位置查询网站来判断了。
422 |
423 | 除了通过 **HTTP 响应头**获取机场三字码外(该功能的实现方式),还可以手动访问 `http://CloudflareIP/cdn-cgi/trace` 来获知 CDN 分配给你的实际节点地区机场三字码。
424 |
425 | > 该功能支持 Cloudflare CDN 和 AWS CloudFront CDN,且这两个 CDN 的机场三字码是通用的(算是惯例)。
426 | > **注意**:如果你要用于筛选 AWS CloudFront CDN 地区,那么要通过 `-url` 参数指定一个使用 AWS CloudFront CDN 的下载测速地址(因为软件默认下载测速地址是 Cloudflare CDN 的)
427 |
428 | ``` bash
429 | # 指定地区名后,延迟测速后得到的结果就都是指定地区的 IP 了(如果没有指定 -dd 的话则会继续进行下载测速)
430 | # 如果延迟测速后结果为 0,则说明没有找到任何一个(未超时可用的)指定地区的 IP。
431 | # 节点地区名为当地 机场三字码,指定多个时用英文逗号分隔,v2.2.3 版本后支持小写
432 |
433 | CloudflareST.exe -httping -cfcolo HKG,KHH,NRT,LAX,SEA,SJC,FRA,MAD
434 |
435 | # 注意,该参数只有在 HTTPing 延迟测速模式下才可用(因为软件是通过 HTTP 链接中的响应头来获得该 IP 的实际地区机场三字码)
436 | ```
437 |
438 | > 两个 CDN 机场三字码通用,因此各地区名可见:https://www.cloudflarestatus.com/
439 |
440 |
441 |
442 | ****
443 |
444 | #### \# 文件相对/绝对路径
445 |
446 |
447 | 「 点击展开 查看内容 」
448 |
449 | ****
450 |
451 | ``` bash
452 | # 指定 IPv4 数据文件,不显示结果直接退出,输出结果到文件(-p 值为 0)
453 | CloudflareST.exe -f 1.txt -p 0 -dd
454 |
455 | # 指定 IPv4 数据文件,不输出结果到文件,直接显示结果(-p 值为 10 条,-o 值为空但引号不能少)
456 | CloudflareST.exe -f 2.txt -o "" -p 10 -dd
457 |
458 | # 指定 IPv4 数据文件 及 输出结果到文件(相对路径,即当前目录下,如含空格请加上引号)
459 | CloudflareST.exe -f 3.txt -o result.txt -dd
460 |
461 |
462 | # 指定 IPv4 数据文件 及 输出结果到文件(相对路径,即当前目录内的 abc 文件夹下,如含空格请加上引号)
463 | # Linux(CloudflareST 程序所在目录内的 abc 文件夹下)
464 | ./CloudflareST -f abc/3.txt -o abc/result.txt -dd
465 |
466 | # Windows(注意是反斜杠)
467 | CloudflareST.exe -f abc\3.txt -o abc\result.txt -dd
468 |
469 |
470 | # 指定 IPv4 数据文件 及 输出结果到文件(绝对路径,即 C:\abc\ 目录下,如含空格请加上引号)
471 | # Linux(/abc/ 目录下)
472 | ./CloudflareST -f /abc/4.txt -o /abc/result.csv -dd
473 |
474 | # Windows(注意是反斜杠)
475 | CloudflareST.exe -f C:\abc\4.txt -o C:\abc\result.csv -dd
476 |
477 |
478 | # 如果要以【绝对路径】运行 CloudflareST,那么 -f / -o 参数中的文件名也必须是【绝对路径】,否则会报错找不到文件!
479 | # Linux(/abc/ 目录下)
480 | /abc/CloudflareST -f /abc/4.txt -o /abc/result.csv -dd
481 |
482 | # Windows(注意是反斜杠)
483 | C:\abc\CloudflareST.exe -f C:\abc\4.txt -o C:\abc\result.csv -dd
484 | ```
485 |
486 |
487 | ****
488 |
489 | #### \# 测速其他端口
490 |
491 |
492 | 「 点击展开 查看内容 」
493 |
494 | ****
495 |
496 | ``` bash
497 | # 如果你想要测速非默认 443 的其他端口,则需要通过 -tp 参数指定(该参数会影响 延迟测速/下载测速 时使用的端口)
498 |
499 | # 如果要延迟测速 80 端口+下载测速(如果 -dd 禁用了下载测速则不需要),那么还需要指定 http:// 协议的下载测速地址才行(且该地址不会强制重定向至 HTTPS,因为那样就变成 443 端口了)
500 | CloudflareST.exe -tp 80 -url http://cdn.cloudflare.steamstatic.com/steam/apps/5952/movie_max.webm
501 |
502 | # 如果是非 80 443 的其他端口,那么需要确定你使用的下载测速地址是否支持通过该非标端口访问。
503 | ```
504 |
505 |
506 |
507 | ****
508 |
509 | #### \# 自定义测速地址
510 |
511 |
512 | 「 点击展开 查看内容 」
513 |
514 | ****
515 |
516 | ``` bash
517 | # 该参数适用于下载测速 及 HTTP 协议的延迟测速,对于后者该地址可以是任意网页 URL(不局限于具体文件地址)
518 |
519 | # 地址要求:可以直接下载、文件大小超过 200MB、用的是 Cloudflare CDN
520 | CloudflareST.exe -url https://cf.xiu2.xyz/url
521 |
522 | # 注意:如果测速地址为 HTTP 协议(该地址不能强制重定向至 HTTPS),记得加上 -tp 80(这个参数会影响 延迟测速/下载测速 时使用的端口),如果是非 80 443 端口,那么需要确定下载测速地址是否支持通过该端口访问。
523 | CloudflareST.exe -tp 80 -url http://cdn.cloudflare.steamstatic.com/steam/apps/5952/movie_max.webm
524 | ```
525 |
526 |
527 |
528 | ****
529 |
530 | #### \# 自定义测速条件(指定 延迟/丢包/下载速度 的目标范围)
531 |
532 |
533 | 「 点击展开 查看内容 」
534 |
535 | ****
536 |
537 | > 注意:延迟测速进度条右边的**可用数量**,仅指延迟测速过程中**未超时的 IP 数量**,和延迟上下限条件无关。
538 |
539 | - 仅指定 **[平均延迟上限]** 条件
540 |
541 | ``` bash
542 | # 平均延迟上限:200 ms,下载速度下限:0 MB/s
543 | # 即找到平均延迟低于 200 ms 的 IP,然后再按延迟从低到高进行 10 次下载测速
544 | CloudflareST.exe -tl 200
545 | ```
546 |
547 | > 如果**没有找到一个满足延迟**条件的 IP,那么不会输出任何内容。
548 |
549 | ****
550 |
551 | - 仅指定 **[平均延迟上限]** 条件,且**只延迟测速,不下载测速**
552 |
553 | ``` bash
554 | # 平均延迟上限:200 ms,下载速度下限:0 MB/s,数量:不知道多少 个
555 | # 即只输出低于 200ms 的 IP,且不再下载测速(因为不再下载测速,所以 -dn 参数就无效了)
556 | CloudflareST.exe -tl 200 -dd
557 | ```
558 |
559 | - 仅指定 **[丢包几率上限]** 条件
560 |
561 | ``` bash
562 | # 丢包几率上限:0.25
563 | # 即找到丢包率低于等于 0.25 的 IP,范围 0.00~1.00,如果 -tlr 0 则代表过滤掉任何丢包的 IP
564 | CloudflareST.exe -tlr 0.25
565 | ```
566 |
567 | ****
568 |
569 | - 仅指定 **[下载速度下限]** 条件
570 |
571 | ``` bash
572 | # 平均延迟上限:9999 ms,下载速度下限:5 MB/s,数量:10 个(可选)
573 | # 即需要找到 10 个平均延迟低于 9999 ms 且下载速度高于 5 MB/s 的 IP 才会停止测速
574 | CloudflareST.exe -sl 5 -dn 10
575 | ```
576 |
577 | > 如果**没有找到一个满足速度**条件的 IP,那么会**忽略条件输出所有 IP 测速结果**(方便你下次测速时调整条件)。
578 |
579 | > 没有指定平均延迟上限时,如果一直**凑不够**满足条件的 IP 数量,就会**一直测速**下去。
580 | > 所以建议**同时指定 [下载速度下限] + [平均延迟上限]**,这样测速到指定延迟上限还没凑够数量,就会终止测速。
581 |
582 | ****
583 |
584 | - 同时指定 **[平均延迟上限] + [下载速度下限]** 条件
585 |
586 | ``` bash
587 | # 平均延迟上限、下载速度下限均支持小数(如 -sl 0.5)
588 | # 平均延迟上限:200 ms,下载速度下限:5.6 MB/s,数量:10 个(可选)
589 | # 即需要找到 10 个平均延迟低于 200 ms 且下载速度高于 5 .6MB/s 的 IP 才会停止测速
590 | CloudflareST.exe -tl 200 -sl 5.6 -dn 10
591 | ```
592 |
593 | > 如果**没有找到一个满足延迟**条件的 IP,那么不会输出任何内容。
594 | > 如果**没有找到一个满足速度**条件的 IP,那么会忽略条件输出所有 IP 测速结果(方便你下次测速时调整条件)。
595 | > 所以建议先不指定条件测速一遍,看看平均延迟和下载速度大概在什么范围,避免指定条件**过低/过高**!
596 |
597 | > 因为 Cloudflare 公开的 IP 段是**回源 IP+任播 IP**,而**回源 IP**是无法使用的,所以下载测速是 0.00。
598 | > 运行时可以加上 `-sl 0.01`(下载速度下限),过滤掉**回源 IP**(下载测速低于 0.01MB/s 的结果)。
599 |
600 |
601 |
602 | ****
603 |
604 | #### \# 单独对一个或多个 IP 测速
605 |
606 |
607 | 「 点击展开 查看内容 」
608 |
609 | ****
610 |
611 | **方式 一**:
612 | 直接通过参数指定要测速的 IP 段数据。
613 | ``` bash
614 | # 先进入 CloudflareST 所在目录,然后运行:
615 | # Windows 系统(在 CMD 中运行)
616 | CloudflareST.exe -ip 1.1.1.1,2.2.2.2/24,2606:4700::/32
617 |
618 | # Linux 系统
619 | ./CloudflareST -ip 1.1.1.1,2.2.2.2/24,2606:4700::/32
620 | ```
621 |
622 | ****
623 |
624 | **方式 二**:
625 | 或者把这些 IP 按如下格式写入到任意文本文件中,例如:`1.txt`
626 |
627 | ```
628 | 1.1.1.1
629 | 1.1.1.200
630 | 1.0.0.1/24
631 | 2606:4700::/32
632 | ```
633 |
634 | > 单个 IP 的话可以省略 `/32` 子网掩码了(即 `1.1.1.1`等同于 `1.1.1.1/32`)。
635 | > 子网掩码 `/24` 指的是这个 IP 最后一段,即 `1.0.0.1~1.0.0.255`。
636 |
637 |
638 | 然后运行 CloudflareST 时加上启动参数 `-f 1.txt` 来指定 IP 段数据文件。
639 |
640 | ``` bash
641 | # 先进入 CloudflareST 所在目录,然后运行:
642 | # Windows 系统(在 CMD 中运行)
643 | CloudflareST.exe -f 1.txt
644 |
645 | # Linux 系统
646 | ./CloudflareST -f 1.txt
647 |
648 | # 对于 1.0.0.1/24 这样的 IP 段只会随机最后一段(1.0.0.1~255),如果要测速该 IP 段中的所有 IP,请加上 -allip 参数。
649 | ```
650 |
651 |
652 |
653 | ****
654 |
655 | #### \# 一劳永逸加速所有使用 Cloudflare CDN 的网站(不需要再一个个添加域名到 Hosts 了)
656 |
657 | 我以前说过,开发该软件项目的目的就是为了通过**改 Hosts 的方式来加速访问使用 Cloudflare CDN 的网站**。
658 |
659 | 但就如 [**#8**](https://github.com/XIU2/CloudflareSpeedTest/issues/8) 所说,一个个添加域名到 Hosts 实在**太麻烦**了,于是我就找到了个**一劳永逸**的办法!可以看这个 [**还在一个个添加 Hosts?完美本地加速所有使用 Cloudflare CDN 的网站方法来了!**](https://github.com/XIU2/CloudflareSpeedTest/discussions/71) 和另一个[依靠本地 DNS 服务来修改域名解析 IP 为自选 IP](https://github.com/XIU2/CloudflareSpeedTest/discussions/317) 的教程。
660 |
661 | ****
662 |
663 | #### \# 自动更新 Hosts
664 |
665 | 考虑到很多人获得最快 Cloudflare CDN IP 后,需要替换 Hosts 文件中的 IP。
666 |
667 | 可以看这个 [**Issues**](https://github.com/XIU2/CloudflareSpeedTest/discussions/312) 获取 **Windows/Linux 自动更新 Hosts 脚本**!
668 |
669 | ****
670 |
671 | ## 问题反馈
672 |
673 | 如果你遇到什么问题,可以先去 [**Issues**](https://github.com/XIU2/CloudflareSpeedTest/issues)、[Discussions](https://github.com/XIU2/CloudflareSpeedTest/discussions) 里看看是否有别人问过了(记得去看下 [**Closed**](https://github.com/XIU2/CloudflareSpeedTest/issues?q=is%3Aissue+is%3Aclosed) 的)。
674 | 如果没找到类似问题,请新开个 [**Issues**](https://github.com/XIU2/CloudflareSpeedTest/issues/new) 来告诉我!
675 |
676 | > [!NOTE]
677 | > **注意**!_与 CloudflareST 本身 `反馈问题、功能建议` 无关的,请前往项目内部 论坛 讨论(顶部的 `💬 Discussions`_
678 |
679 | ****
680 |
681 | ## 如果帮到你的话就 "打赏" 一下吧~🎉✨
682 |
683 | 
684 |
685 | ****
686 |
687 | ## 衍生项目
688 |
689 | - _https://github.com/xianshenglu/cloudflare-ip-tester-app_
690 | _**CloudflareST 安卓版 APP [#202](https://github.com/XIU2/CloudflareSpeedTest/discussions/320)**_
691 |
692 | - _https://github.com/mingxiaoyu/luci-app-cloudflarespeedtest_
693 | _**CloudflareST OpenWrt 路由器插件版 [#174](https://github.com/XIU2/CloudflareSpeedTest/discussions/319)**_
694 |
695 | - _https://github.com/immortalwrt-collections/openwrt-cdnspeedtest_
696 | _**CloudflareST OpenWrt 原生编译版本 [#64](https://github.com/XIU2/CloudflareSpeedTest/discussions/64)**_
697 |
698 | - _https://github.com/hoseinnikkhah/CloudflareSpeedTest-English_
699 | _**English language version of CloudflareST (Text language differences only) [#64](https://github.com/XIU2/CloudflareSpeedTest/issues/68)**_
700 |
701 | > _此处仅收集了在本项目中宣传过的部分 CloudflareST 相关衍生项目,如果有遗漏可以告诉我~_
702 |
703 | ****
704 |
705 | ## 感谢项目
706 |
707 | - _https://github.com/Spedoske/CloudflareScanner_
708 |
709 | > _因为该项目已经很长时间没更新了,而我又产生了很多功能需求,所以我临时学了下 Go 语言就上手了(菜)..._
710 | > _本软件基于该项目制作,但**已添加大量功能及修复 BUG**,并根据大家的使用反馈积极添加、优化功能(闲)..._
711 |
712 | ****
713 |
714 | ## 手动编译
715 |
716 |
717 | 「 点击展开 查看内容 」
718 |
719 | ****
720 |
721 | 为了方便,我是在编译的时候将版本号写入代码中的 version 变量,因此你手动编译时,需要像下面这样在 `go build` 命令后面加上 `-ldflags` 参数来指定版本号:
722 |
723 | ```bash
724 | go build -ldflags "-s -w -X main.version=v2.3.3"
725 | # 在 CloudflareSpeedTest 目录中通过命令行(例如 CMD、Bat 脚本)运行该命令,即可编译一个可在和当前设备同样系统、位数、架构的环境下运行的二进制程序(Go 会自动检测你的系统位数、架构)且版本号为 v2.3.3
726 | ```
727 |
728 | 如果想要在 Windows 64位系统下编译**其他系统、架构、位数**,那么需要指定 **GOOS** 和 **GOARCH** 变量。
729 |
730 | 例如在 Windows 系统下编译一个适用于 **Linux 系统 amd 架构 64 位**的二进制程序:
731 |
732 | ```bat
733 | SET GOOS=linux
734 | SET GOARCH=amd64
735 | go build -ldflags "-s -w -X main.version=v2.3.3"
736 | ```
737 |
738 | 例如在 Linux 系统下编译一个适用于 **Windows 系统 amd 架构 32 位**的二进制程序:
739 |
740 | ```bash
741 | GOOS=windows
742 | GOARCH=386
743 | go build -ldflags "-s -w -X main.version=v2.3.3"
744 | ```
745 |
746 | > 可以运行 `go tool dist list` 来查看当前 Go 版本支持编译哪些组合。
747 |
748 | ****
749 |
750 | 当然,为了方便批量编译,我会专门指定一个变量为版本号,后续编译直接调用该版本号变量即可。
751 | 同时,批量编译的话,还需要分开放到不同文件夹才行(或者文件名不同),需要加上 `-o` 参数指定。
752 |
753 | ```bat
754 | :: Windows 系统下是这样:
755 | SET version=v2.3.3
756 | SET GOOS=linux
757 | SET GOARCH=amd64
758 | go build -o Releases\CloudflareST_linux_amd64\CloudflareST -ldflags "-s -w -X main.version=%version%"
759 | ```
760 |
761 | ```bash
762 | # Linux 系统下是这样:
763 | version=v2.3.3
764 | GOOS=windows
765 | GOARCH=386
766 | go build -o Releases/CloudflareST_windows_386/CloudflareST.exe -ldflags "-s -w -X main.version=${version}"
767 | ```
768 |
769 |
770 |
771 | ****
772 |
773 | ## License
774 |
775 | The GPL-3.0 License.
776 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/XIU2/CloudflareSpeedTest
2 |
3 | go 1.14
4 |
5 | require (
6 | github.com/VividCortex/ewma v1.1.1
7 | github.com/cheggaaa/pb/v3 v3.0.4
8 | )
9 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/VividCortex/ewma v1.1.1 h1:MnEK4VOv6n0RSY4vtRe3h11qjxL3+t0B8yOL8iMXdcM=
2 | github.com/VividCortex/ewma v1.1.1/go.mod h1:2Tkkvm3sRDVXaiyucHiACn4cqf7DpdyLvmxzcbUokwA=
3 | github.com/cheggaaa/pb/v3 v3.0.4 h1:QZEPYOj2ix6d5oEg63fbHmpolrnNiwjUsk+h74Yt4bM=
4 | github.com/cheggaaa/pb/v3 v3.0.4/go.mod h1:7rgWxLrAUcFMkvJuv09+DYi7mMUYi8nO9iOWcvGJPfw=
5 | github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys=
6 | github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
7 | github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU=
8 | github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
9 | github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
10 | github.com/mattn/go-isatty v0.0.10 h1:qxFzApOv4WsAL965uUPIsXzAKCZxN2p9UqdhFS4ZW10=
11 | github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
12 | github.com/mattn/go-runewidth v0.0.7 h1:Ei8KR0497xHyKJPAv59M1dkC+rOZCMBJ+t3fZ+twI54=
13 | github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
14 | golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
15 | golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
16 | golang.org/x/sys v0.0.0-20191128015809-6d18c012aee9 h1:ZBzSG/7F4eNKz2L3GE9o300RX0Az1Bw5HF7PDraD+qU=
17 | golang.org/x/sys v0.0.0-20191128015809-6d18c012aee9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
18 |
--------------------------------------------------------------------------------
/ip.txt:
--------------------------------------------------------------------------------
1 | 173.245.48.0/20
2 | 103.21.244.0/22
3 | 103.22.200.0/22
4 | 103.31.4.0/22
5 | 141.101.64.0/18
6 | 108.162.192.0/18
7 | 190.93.240.0/20
8 | 188.114.96.0/20
9 | 197.234.240.0/22
10 | 198.41.128.0/17
11 | 162.158.0.0/15
12 | 104.16.0.0/12
13 | 172.64.0.0/17
14 | 172.64.128.0/18
15 | 172.64.192.0/19
16 | 172.64.224.0/22
17 | 172.64.229.0/24
18 | 172.64.230.0/23
19 | 172.64.232.0/21
20 | 172.64.240.0/21
21 | 172.64.248.0/21
22 | 172.65.0.0/16
23 | 172.66.0.0/16
24 | 172.67.0.0/16
25 | 131.0.72.0/22
--------------------------------------------------------------------------------
/ipv6.txt:
--------------------------------------------------------------------------------
1 | 2400:cb00:2049::/48
2 | 2400:cb00:f00e::/48
3 | 2606:4700::/32
4 | 2606:4700:10::/48
5 | 2606:4700:130::/48
6 | 2606:4700:3000::/48
7 | 2606:4700:3001::/48
8 | 2606:4700:3002::/48
9 | 2606:4700:3003::/48
10 | 2606:4700:3004::/48
11 | 2606:4700:3005::/48
12 | 2606:4700:3006::/48
13 | 2606:4700:3007::/48
14 | 2606:4700:3008::/48
15 | 2606:4700:3009::/48
16 | 2606:4700:3010::/48
17 | 2606:4700:3011::/48
18 | 2606:4700:3012::/48
19 | 2606:4700:3013::/48
20 | 2606:4700:3014::/48
21 | 2606:4700:3015::/48
22 | 2606:4700:3016::/48
23 | 2606:4700:3017::/48
24 | 2606:4700:3018::/48
25 | 2606:4700:3019::/48
26 | 2606:4700:3020::/48
27 | 2606:4700:3021::/48
28 | 2606:4700:3022::/48
29 | 2606:4700:3023::/48
30 | 2606:4700:3024::/48
31 | 2606:4700:3025::/48
32 | 2606:4700:3026::/48
33 | 2606:4700:3027::/48
34 | 2606:4700:3028::/48
35 | 2606:4700:3029::/48
36 | 2606:4700:3030::/48
37 | 2606:4700:3031::/48
38 | 2606:4700:3032::/48
39 | 2606:4700:3033::/48
40 | 2606:4700:3034::/48
41 | 2606:4700:3035::/48
42 | 2606:4700:3036::/48
43 | 2606:4700:3037::/48
44 | 2606:4700:3038::/48
45 | 2606:4700:3039::/48
46 | 2606:4700:a0::/48
47 | 2606:4700:a1::/48
48 | 2606:4700:a8::/48
49 | 2606:4700:a9::/48
50 | 2606:4700:a::/48
51 | 2606:4700:b::/48
52 | 2606:4700:c::/48
53 | 2606:4700:d0::/48
54 | 2606:4700:d1::/48
55 | 2606:4700:d::/48
56 | 2606:4700:e0::/48
57 | 2606:4700:e1::/48
58 | 2606:4700:e2::/48
59 | 2606:4700:e3::/48
60 | 2606:4700:e4::/48
61 | 2606:4700:e5::/48
62 | 2606:4700:e6::/48
63 | 2606:4700:e7::/48
64 | 2606:4700:e::/48
65 | 2606:4700:f1::/48
66 | 2606:4700:f2::/48
67 | 2606:4700:f3::/48
68 | 2606:4700:f4::/48
69 | 2606:4700:f5::/48
70 | 2606:4700:f::/48
71 | 2803:f800:50::/48
72 | 2803:f800:51::/48
73 | 2a06:98c1:3100::/48
74 | 2a06:98c1:3101::/48
75 | 2a06:98c1:3102::/48
76 | 2a06:98c1:3103::/48
77 | 2a06:98c1:3104::/48
78 | 2a06:98c1:3105::/48
79 | 2a06:98c1:3106::/48
80 | 2a06:98c1:3107::/48
81 | 2a06:98c1:3108::/48
82 | 2a06:98c1:3109::/48
83 | 2a06:98c1:310a::/48
84 | 2a06:98c1:310b::/48
85 | 2a06:98c1:310c::/48
86 | 2a06:98c1:310d::/48
87 | 2a06:98c1:310e::/48
88 | 2a06:98c1:310f::/48
89 | 2a06:98c1:3120::/48
90 | 2a06:98c1:3121::/48
91 | 2a06:98c1:3122::/48
92 | 2a06:98c1:3123::/48
93 | 2a06:98c1:3200::/48
94 | 2a06:98c1:50::/48
95 | 2a06:98c1:51::/48
96 | 2a06:98c1:54::/48
97 | 2a06:98c1:58::/48
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "fmt"
6 | "io"
7 | "net/http"
8 | "os"
9 | "runtime"
10 | "time"
11 |
12 | "github.com/XIU2/CloudflareSpeedTest/task"
13 | "github.com/XIU2/CloudflareSpeedTest/utils"
14 | )
15 |
16 | var (
17 | version, versionNew string
18 | )
19 |
20 | func init() {
21 | var printVersion bool
22 | var help = `
23 | CloudflareSpeedTest ` + version + `
24 | 测试 Cloudflare CDN 所有 IP 的延迟和速度,获取最快 IP (IPv4+IPv6)!
25 | https://github.com/XIU2/CloudflareSpeedTest
26 |
27 | 参数:
28 | -n 200
29 | 延迟测速线程;越多延迟测速越快,性能弱的设备 (如路由器) 请勿太高;(默认 200 最多 1000)
30 | -t 4
31 | 延迟测速次数;单个 IP 延迟测速的次数;(默认 4 次)
32 | -dn 10
33 | 下载测速数量;延迟测速并排序后,从最低延迟起下载测速的数量;(默认 10 个)
34 | -dt 10
35 | 下载测速时间;单个 IP 下载测速最长时间,不能太短;(默认 10 秒)
36 | -tp 443
37 | 指定测速端口;延迟测速/下载测速时使用的端口;(默认 443 端口)
38 | -url https://cf.xiu2.xyz/url
39 | 指定测速地址;延迟测速(HTTPing)/下载测速时使用的地址,默认地址不保证可用性,建议自建;
40 |
41 | -httping
42 | 切换测速模式;延迟测速模式改为 HTTP 协议,所用测试地址为 [-url] 参数;(默认 TCPing)
43 | -httping-code 200
44 | 有效状态代码;HTTPing 延迟测速时网页返回的有效 HTTP 状态码,仅限一个;(默认 200 301 302)
45 | -cfcolo HKG,KHH,NRT,LAX,SEA,SJC,FRA,MAD
46 | 匹配指定地区;地区名为当地机场三字码,英文逗号分隔,仅 HTTPing 模式可用;(默认 所有地区)
47 |
48 | -tl 200
49 | 平均延迟上限;只输出低于指定平均延迟的 IP,各上下限条件可搭配使用;(默认 9999 ms)
50 | -tll 40
51 | 平均延迟下限;只输出高于指定平均延迟的 IP;(默认 0 ms)
52 | -tlr 0.2
53 | 丢包几率上限;只输出低于/等于指定丢包率的 IP,范围 0.00~1.00,0 过滤掉任何丢包的 IP;(默认 1.00)
54 | -sl 5
55 | 下载速度下限;只输出高于指定下载速度的 IP,凑够指定数量 [-dn] 才会停止测速;(默认 0.00 MB/s)
56 |
57 | -p 10
58 | 显示结果数量;测速后直接显示指定数量的结果,为 0 时不显示结果直接退出;(默认 10 个)
59 | -f ip.txt
60 | IP段数据文件;如路径含有空格请加上引号;支持其他 CDN IP段;(默认 ip.txt)
61 | -ip 1.1.1.1,2.2.2.2/24,2606:4700::/32
62 | 指定IP段数据;直接通过参数指定要测速的 IP 段数据,英文逗号分隔;(默认 空)
63 | -o result.csv
64 | 写入结果文件;如路径含有空格请加上引号;值为空时不写入文件 [-o ""];(默认 result.csv)
65 |
66 | -dd
67 | 禁用下载测速;禁用后测速结果会按延迟排序 (默认按下载速度排序);(默认 启用)
68 | -allip
69 | 测速全部的IP;对 IP 段中的每个 IP (仅支持 IPv4) 进行测速;(默认 每个 /24 段随机测速一个 IP)
70 |
71 | -v
72 | 打印程序版本 + 检查版本更新
73 | -h
74 | 打印帮助说明
75 | `
76 | var minDelay, maxDelay, downloadTime int
77 | var maxLossRate float64
78 | flag.IntVar(&task.Routines, "n", 200, "延迟测速线程")
79 | flag.IntVar(&task.PingTimes, "t", 4, "延迟测速次数")
80 | flag.IntVar(&task.TestCount, "dn", 10, "下载测速数量")
81 | flag.IntVar(&downloadTime, "dt", 10, "下载测速时间")
82 | flag.IntVar(&task.TCPPort, "tp", 443, "指定测速端口")
83 | flag.StringVar(&task.URL, "url", "https://cf.xiu2.xyz/url", "指定测速地址")
84 |
85 | flag.BoolVar(&task.Httping, "httping", false, "切换测速模式")
86 | flag.IntVar(&task.HttpingStatusCode, "httping-code", 0, "有效状态代码")
87 | flag.StringVar(&task.HttpingCFColo, "cfcolo", "", "匹配指定地区")
88 |
89 | flag.IntVar(&maxDelay, "tl", 9999, "平均延迟上限")
90 | flag.IntVar(&minDelay, "tll", 0, "平均延迟下限")
91 | flag.Float64Var(&maxLossRate, "tlr", 1, "丢包几率上限")
92 | flag.Float64Var(&task.MinSpeed, "sl", 0, "下载速度下限")
93 |
94 | flag.IntVar(&utils.PrintNum, "p", 10, "显示结果数量")
95 | flag.StringVar(&task.IPFile, "f", "ip.txt", "IP段数据文件")
96 | flag.StringVar(&task.IPText, "ip", "", "指定IP段数据")
97 | flag.StringVar(&utils.Output, "o", "result.csv", "输出结果文件")
98 |
99 | flag.BoolVar(&task.Disable, "dd", false, "禁用下载测速")
100 | flag.BoolVar(&task.TestAll, "allip", false, "测速全部 IP")
101 |
102 | flag.BoolVar(&printVersion, "v", false, "打印程序版本")
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("[小提示] 在使用 [-sl] 参数时,建议搭配 [-tl] 参数,以避免因凑不够 [-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("检查版本更新中...")
118 | checkUpdate()
119 | if versionNew != "" {
120 | fmt.Printf("*** 发现新版本 [%s]!请前往 [https://github.com/XIU2/CloudflareSpeedTest] 更新! ***", versionNew)
121 | } else {
122 | fmt.Println("当前为最新版本 [" + version + "]!")
123 | }
124 | os.Exit(0)
125 | }
126 | }
127 |
128 | func main() {
129 | task.InitRandSeed() // 置随机数种子
130 |
131 | fmt.Printf("# XIU2/CloudflareSpeedTest %s \n\n", version)
132 |
133 | // 开始延迟测速 + 过滤延迟/丢包
134 | pingData := task.NewPing().Run().FilterDelay().FilterLossRate()
135 | // 开始下载测速
136 | speedData := task.TestDownloadSpeed(pingData)
137 | utils.ExportCsv(speedData) // 输出文件
138 | speedData.Print() // 打印结果
139 |
140 | if versionNew != "" {
141 | fmt.Printf("\n*** 发现新版本 [%s]!请前往 [https://github.com/XIU2/CloudflareSpeedTest] 更新! ***\n", versionNew)
142 | }
143 | endPrint()
144 | }
145 |
146 | func endPrint() {
147 | if utils.NoPrintResult() {
148 | return
149 | }
150 | if runtime.GOOS == "windows" { // 如果是 Windows 系统,则需要按下 回车键 或 Ctrl+C 退出(避免通过双击运行时,测速完毕后直接关闭)
151 | fmt.Printf("按下 回车键 或 Ctrl+C 退出。")
152 | fmt.Scanln()
153 | }
154 | }
155 |
156 | // 检查更新
157 | func checkUpdate() {
158 | timeout := 10 * time.Second
159 | client := http.Client{Timeout: timeout}
160 | res, err := client.Get("https://api.xiu2.xyz/ver/cloudflarespeedtest.txt")
161 | if err != nil {
162 | return
163 | }
164 | // 读取资源数据 body: []byte
165 | body, err := io.ReadAll(res.Body)
166 | if err != nil {
167 | return
168 | }
169 | // 关闭资源流
170 | defer res.Body.Close()
171 | if string(body) != version {
172 | versionNew = string(body)
173 | }
174 | }
175 |
--------------------------------------------------------------------------------
/script/README.md:
--------------------------------------------------------------------------------
1 | # XIU2/CloudflareSpeedTest - Script(脚本)
2 |
3 | 这里都是一些通过调用 **CloudflareST** 并**扩展实现更多个性化功能**的脚本。
4 |
5 | ****
6 | > [!TIP]
7 | > 我之所以将 CloudflareST 制作为一个**命令行程序**,就是考虑到**通用性**,因为毕竟不可能把所有需求都塞到软件内(特别是一些**个性化、小众**的需求),这样增加维护难度和精力不说,还会导致软件异常臃肿(`“变成我讨厌的样子”`),而命令行程序的优势之一就在于**可以很方便的和其他软件、脚本搭配使用**。
8 |
9 | 比如像下面这些我写的几个脚本,就是把一些需求以外置脚本方式实现。
10 |
11 | > 即脚本调用 CloudflareST 测速并获取结果,然后***按照自己的需求自由决定***如何处理得到的测速结果(比如修改 Hosts 等)。
12 |
13 | 总的来说,我写的这几个脚本都比较简单,功能也很单一,除了满足部分用户的需求外,***更像是一个 CloudflareST 与脚本搭配使用的示例参考***,对于一些会写脚本、软件的用户来说,完全可以**自给自足**来实现一些个性化需求。
14 |
15 | 当然,如果你有一些自用好用的脚本也可以通过 [**Issues**](https://github.com/XIU2/CloudflareSpeedTest/issues)、[**Discussions**](https://github.com/XIU2/CloudflareSpeedTest/discussions) 或 **Pull requests** 发给我添加到这里让更多人用到!
16 |
17 | > 小提示:点击↗右上角的三横杠图标按钮即可查看目录~
18 |
19 | ****
20 | ## 📑 cfst_hosts.sh / cfst_hosts.bat (已内置压缩包)
21 |
22 | 脚本会运行 CloudflareST 获得最快 IP,并替换掉 Hosts 文件中的旧 CDN IP。
23 |
24 | > **作者:**[@XIU2](https://github.com/xiu2)
25 | > **使用说明/问题反馈:https://github.com/XIU2/CloudflareSpeedTest/discussions/312**
26 |
27 |
28 | 「 更新日志」
29 |
30 | ****
31 |
32 | #### 2021年12月17日,版本 v1.0.6
33 | - **1. 优化** [找不到满足条件的 IP 就一直循环测速] 功能,在指定下载测速下限时没有重新测速的问题(默认注释)
34 |
35 | #### 2021年12月17日,版本 v1.0.3
36 | - **1. 新增** 找不到满足条件的 IP 就一直循环测速功能(默认注释)
37 | - **2. 优化** 代码
38 |
39 | #### 2021年09月29日,版本 v1.0.2
40 | - **1. 修复** 当测速结果 IP 数量为 0 时,脚本没有退出的问题
41 |
42 | #### 2021年04月29日,版本 v1.0.1
43 | - **1. 优化** 不再需要加上 -p 0 参数来避免回车键退出了(现在可以即显示结果,又不用担心回车键退出程序)
44 |
45 | #### 2021年01月28日,版本 v1.0.0
46 | - **1. 发布** 第一个版本
47 |
48 |
49 |
50 | ****
51 |
52 | ## 📑 cfst_3proxy.bat (已内置压缩包)
53 |
54 | 脚本会运行 CloudflareST 测速后获取最快 IP 并替换 3Proxy 配置文件中的旧 Cloudflare CDN IP。
55 | 可以把所有 Cloudflare CDN IP 都重定向至最快 IP,实现一劳永逸的加速所有使用 Cloudflare CDN 的网站(不需要一个个添加域名到 Hosts 了)。
56 |
57 | > **作者:**[@XIU2](https://github.com/xiu2)
58 | > **使用说明/问题反馈:https://github.com/XIU2/CloudflareSpeedTest/discussions/71**
59 |
60 |
61 | 「 更新日志」
62 |
63 | ****
64 |
65 | #### 2021年12月17日,版本 v1.0.5
66 | - **1. 优化** [找不到满足条件的 IP 就一直循环测速] 功能,在指定下载测速下限时没有重新测速的问题(默认注释)
67 |
68 | #### 2021年12月17日,版本 v1.0.4
69 | - **1. 新增** 找不到满足条件的 IP 就一直循环测速功能(默认注释)
70 | - **2. 优化** 代码
71 |
72 | #### 2021年09月29日,版本 v1.0.3
73 | - **1. 修复** 当测速结果 IP 数量为 0 时,脚本没有退出的问题
74 |
75 | #### 2021年04月29日,版本 v1.0.2
76 | - **1. 优化** 不再需要加上 -p 0 参数来避免回车键退出了(现在可以即显示结果,又不用担心回车键退出程序)
77 |
78 | #### 2021年03月16日,版本 v1.0.1
79 | - **1. 优化** 代码及注释内容
80 |
81 | #### 2021年03月13日,版本 v1.0.0
82 | - **1. 发布** 第一个版本
83 |
84 |
85 |
86 | ****
87 |
88 | ## 📑 cfst_dnspod.sh
89 |
90 | 如果你的域名托管在 **dnspod**,则可以通过 dnspod 官方提供的 API 来自动更新域名解析记录!
91 | 脚本会运行 CloudflareST 测速获得最快 IP,并通过 Cloudflare API 来更新域名解析记录为这个最快 IP。
92 |
93 | > **作者:**[@imashen](https://github.com/imashen)
94 | > **使用说明/问题反馈:https://github.com/XIU2/CloudflareSpeedTest/pull/533**
95 |
96 |
97 | 「 更新日志」
98 |
99 | ****
100 |
101 | #### 2024年08月06日,版本 v1.0.0
102 | - **1. 发布** 第一个版本
103 |
104 |
105 |
106 | ****
107 |
108 | ## 📑 cfst_ddns.sh / cfst_ddns.bat
109 |
110 | 如果你的域名托管在 **Cloudflare**,则可以通过 Cloudflare 官方提供的 API 来自动更新域名解析记录!
111 | 脚本会运行 CloudflareST 测速获得最快 IP,并通过 Cloudflare API 来更新域名解析记录为这个最快 IP。
112 |
113 | > **作者:**[@XIU2](https://github.com/xiu2)
114 | > **使用说明/问题反馈:https://github.com/XIU2/CloudflareSpeedTest/discussions/481**
115 |
116 |
117 | 「 更新日志」
118 |
119 | ****
120 |
121 | #### 2024年10月06日,版本 v1.0.5
122 | - **1. 新增** 支持 API 令牌方式(相比 API 密钥这种全局权限的,API 令牌可以自由控制权限)
123 |
124 | #### 2021年12月17日,版本 v1.0.4
125 | - **1. 新增** 找不到满足条件的 IP 就一直循环测速功能(默认注释)
126 | - **2. 优化** 代码
127 |
128 | #### 2021年09月29日,版本 v1.0.3
129 | - **1. 修复** 当测速结果 IP 数量为 0 时,脚本没有退出的问题
130 |
131 | #### 2021年04月29日,版本 v1.0.2
132 | - **1. 优化** 不再需要加上 -p 0 参数来避免回车键退出了(现在可以即显示结果,又不用担心回车键退出程序)
133 |
134 | #### 2021年01月27日,版本 v1.0.1
135 | - **1. 优化** 配置从文件中读取
136 |
137 | #### 2021年01月26日,版本 v1.0.0
138 | - **1. 发布** 第一个版本
139 |
140 |
141 |
142 | ****
143 |
144 | ## 📑 cfst_dnsmasq.sh
145 |
146 | 脚本会运行 CloudflareST 测速后获取最快 IP 并替换 dnsmasq 配置文件中的旧 Cloudflare CDN IP。
147 |
148 | > **作者:**[@Sving1024](https://github.com/Sving1024)
149 | > **使用说明/问题反馈:https://github.com/XIU2/CloudflareSpeedTest/discussions/566**
150 |
151 |
152 | 「 更新日志」
153 |
154 | ****
155 |
156 | #### 2025年01月22日,版本 v1.0.1
157 | - **1. 修复** IPv6 的问题
158 |
159 | #### 2024年12月28日,版本 v1.0.0
160 | - **1. 发布** 第一个版本
161 |
162 |
163 |
164 | ****
165 |
166 | ## 功能建议/问题反馈
167 |
168 | 如果这些脚本使用过程中你遇到了什么问题,可以先去脚本对应的 **`使用说明`** 帖子里看看是否有别人问过了。
169 | 如果没找到类似问题,那么就在脚本对应的 **`使用说明`** 帖子里直接评论问作者吧。
--------------------------------------------------------------------------------
/script/cfst_3proxy.bat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XIU2/CloudflareSpeedTest/04da9f56595fc7063a568f521e59f1b260cd308a/script/cfst_3proxy.bat
--------------------------------------------------------------------------------
/script/cfst_ddns.bat:
--------------------------------------------------------------------------------
1 | :: --------------------------------------------------------------
2 | :: 项目: CloudflareSpeedTest 自动更新域名解析记录
3 | :: 版本: 1.0.5
4 | :: 作者: XIU2
5 | :: 项目: https://github.com/XIU2/CloudflareSpeedTest
6 | :: --------------------------------------------------------------
7 | @echo off
8 | Setlocal Enabledelayedexpansion
9 |
10 | :: 这里可以自己添加、修改 CloudflareST 的运行参数,echo.| 的作用是自动回车退出程序(不再需要加上 -p 0 参数了)
11 | echo.|CloudflareST.exe -o "result_ddns.txt"
12 |
13 | :: 判断结果文件是否存在,如果不存在说明结果为 0
14 | if not exist result_ddns.txt (
15 | echo.
16 | echo CloudflareST 测速结果 IP 数量为 0,跳过下面步骤...
17 | goto :END
18 | )
19 |
20 | for /f "tokens=1 delims=," %%i in (result_ddns.txt) do (
21 | Set /a n+=1
22 | If !n!==2 (
23 | Echo %%i
24 | if "%%i"=="" (
25 | echo.
26 | echo CloudflareST 测速结果 IP 数量为 0,跳过下面步骤...
27 | goto :END
28 | )
29 | :: API 密钥方式(全局权限)
30 | curl -X PUT "https://api.cloudflare.com/client/v4/zones/域名ID/dns_records/域名解析记录ID" ^
31 | -H "X-Auth-Email: 账号邮箱" ^
32 | -H "X-Auth-Key: 前面获取的 API 密钥" ^
33 | -H "Content-Type: application/json" ^
34 | --data "{\"type\":\"A\",\"name\":\"完整域名\",\"content\":\"%%i\",\"ttl\":1,\"proxied\":true}"
35 | :: API 令牌方式(自定义权限),如果要使用这种方式,可以把上面的删除或注释,然后把下面的行首 "::" 注释符删除即可。
36 | :: curl -X PUT "https://api.cloudflare.com/client/v4/zones/域名ID/dns_records/域名解析记录ID" ^
37 | :: -H "Authorization: Bearer 前面获取的 API 令牌" ^
38 | :: -H "Content-Type: application/json" ^
39 | :: --data "{\"type\":\"A\",\"name\":\"完整域名\",\"content\":\"%%i\",\"ttl\":1,\"proxied\":true}"
40 |
41 | goto :END
42 | )
43 | )
44 | :END
45 | pause
--------------------------------------------------------------------------------
/script/cfst_ddns.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
3 | export PATH
4 | # --------------------------------------------------------------
5 | # 项目: CloudflareSpeedTest 自动更新域名解析记录
6 | # 版本: 1.0.5
7 | # 作者: XIU2
8 | # 项目: https://github.com/XIU2/CloudflareSpeedTest
9 | # --------------------------------------------------------------
10 |
11 | _READ() {
12 | [[ ! -e "cfst_ddns.conf" ]] && echo -e "[错误] 配置文件不存在 [cfst_ddns.conf] !" && exit 1
13 | CONFIG=$(cat "cfst_ddns.conf")
14 | FOLDER=$(echo "${CONFIG}"|grep 'FOLDER='|awk -F '=' '{print $NF}')
15 | [[ -z "${FOLDER}" ]] && echo -e "[错误] 缺少配置项 [FOLDER] !" && exit 1
16 | ZONE_ID=$(echo "${CONFIG}"|grep 'ZONE_ID='|awk -F '=' '{print $NF}')
17 | [[ -z "${ZONE_ID}" ]] && echo -e "[错误] 缺少配置项 [ZONE_ID] !" && exit 1
18 | DNS_RECORDS_ID=$(echo "${CONFIG}"|grep 'DNS_RECORDS_ID='|awk -F '=' '{print $NF}')
19 | [[ -z "${DNS_RECORDS_ID}" ]] && echo -e "[错误] 缺少配置项 [DNS_RECORDS_ID] !" && exit 1
20 | KEY=$(echo "${CONFIG}"|grep 'KEY='|awk -F '=' '{print $NF}')
21 | [[ -z "${KEY}" ]] && echo -e "[错误] 缺少配置项 [KEY] !" && exit 1
22 | EMAIL=$(echo "${CONFIG}"|grep 'EMAIL='|awk -F '=' '{print $NF}')
23 | [[ -z "${EMAIL}" ]] && echo -e "[信息] 缺少配置项 [EMAIL],由 [API 密钥] 方式转为 [API 令牌] 方式!"
24 | TYPE=$(echo "${CONFIG}"|grep 'TYPE='|awk -F '=' '{print $NF}')
25 | [[ -z "${TYPE}" ]] && echo -e "[错误] 缺少配置项 [TYPE] !" && exit 1
26 | NAME=$(echo "${CONFIG}"|grep 'NAME='|awk -F '=' '{print $NF}')
27 | [[ -z "${NAME}" ]] && echo -e "[错误] 缺少配置项 [NAME] !" && exit 1
28 | TTL=$(echo "${CONFIG}"|grep 'TTL='|awk -F '=' '{print $NF}')
29 | [[ -z "${TTL}" ]] && echo -e "[错误] 缺少配置项 [TTL] !" && exit 1
30 | PROXIED=$(echo "${CONFIG}"|grep 'PROXIED='|awk -F '=' '{print $NF}')
31 | [[ -z "${PROXIED}" ]] && echo -e "[错误] 缺少配置项 [PROXIED] !" && exit 1
32 | }
33 |
34 | _UPDATE() {
35 | # 这里可以自己添加、修改 CloudflareST 的运行参数
36 | ./CloudflareST -o "result_ddns.txt"
37 |
38 | # 判断结果文件是否存在,如果不存在说明结果为 0
39 | [[ ! -e "result_ddns.txt" ]] && echo "CloudflareST 测速结果 IP 数量为 0,跳过下面步骤..." && exit 0
40 |
41 | CONTENT=$(sed -n "2,1p" result_ddns.txt | awk -F, '{print $1}')
42 | if [[ -z "${CONTENT}" ]]; then
43 | echo "CloudflareST 测速结果 IP 数量为 0,跳过下面步骤..."
44 | exit 0
45 | fi
46 | # 如果 EMAIL 变量是空的,那么就代表要使用 API 令牌方式
47 | if [[ -n "${EMAIL}" ]]; then
48 | # API 密钥方式(全局权限)
49 | curl -X PUT "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records/${DNS_RECORDS_ID}" \
50 | -H "X-Auth-Email: ${EMAIL}" \
51 | -H "X-Auth-Key: ${KEY}" \
52 | -H "Content-Type: application/json" \
53 | --data "{\"type\":\"${TYPE}\",\"name\":\"${NAME}\",\"content\":\"${CONTENT}\",\"ttl\":${TTL},\"proxied\":${PROXIED}}"
54 | else
55 | # API 令牌方式(自定义权限)
56 | curl -X PUT "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records/${DNS_RECORDS_ID}" \
57 | -H "Authorization: Bearer ${KEY}" \
58 | -H "Content-Type: application/json" \
59 | --data "{\"type\":\"${TYPE}\",\"name\":\"${NAME}\",\"content\":\"${CONTENT}\",\"ttl\":${TTL},\"proxied\":${PROXIED}}"
60 | fi
61 | }
62 |
63 | _READ
64 | cd "${FOLDER}"
65 | _UPDATE
--------------------------------------------------------------------------------
/script/cfst_dnsmasq.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
3 | export PATH
4 | # --------------------------------------------------------------
5 | # 项目: CloudflareSpeedTest 自动更新 dnsmasq 配置文件
6 | # 版本: 1.0.1
7 | # 作者: XIU2,Sving1024
8 | # 项目: https://github.com/XIU2/CloudflareSpeedTest
9 | # --------------------------------------------------------------
10 |
11 | _UPDATE() {
12 | echo -e "开始测速..."
13 | BESTIP=""
14 | BESTIP_IPV6="::"
15 | # 这里可以自己添加、修改 CloudflareST 的运行参数
16 | ./CloudflareST -o "result_hosts.txt"
17 | # 需要测速 IPv6 请取消注释
18 | #./CloudflareST -o "result_hosts_ipv6.txt" -f ipv6.txt
19 |
20 | # 如果需要 "找不到满足条件的 IP 就一直循环测速下去",那么可以将下面的两个 exit 0 改为 _UPDATE 即可
21 | [[ ! -e "result_hosts.txt" ]] && echo "CloudflareST 测速结果 IP 数量为 0,跳过下面步骤..." && exit 0
22 |
23 | # 下面这行代码是 "找不到满足条件的 IP 就一直循环测速下去" 才需要的代码
24 | # 考虑到当指定了下载速度下限,但一个满足全部条件的 IP 都没找到时,CloudflareST 就会输出所有 IP 结果
25 | # 因此当你指定 -sl 参数时,需要移除下面这段代码开头的 # 井号注释符,来做文件行数判断(比如下载测速数量:10 个,那么下面的值就设在为 11)
26 | #[[ $(cat result_hosts.txt|wc -l) > 11 ]] && echo "CloudflareST 测速结果没有找到一个完全满足条件的 IP,重新测速..." && _UPDATE
27 |
28 | BESTIP=$(sed -n "2,1p" result_hosts.txt | awk -F, '{print $1}')
29 | # 需要测速 IPv6 请取消注释
30 | #BESTIP_IPV6=$(sed -n "2,1p" result_hosts_ipv6.txt | awk -F, '{print $1}')
31 |
32 | if [[ -z "${BESTIP}" ]]; then
33 | echo "CloudflareST 测速结果 IP 数量为 0,跳过下面步骤..."
34 | exit 0
35 | fi
36 | echo ${BESTIP} > nowip_hosts.txt
37 | echo -e "最优 IPv4 IP 为 ${BESTIP}\n"
38 | # 需要测速 IPv6 请取消注释
39 | #echo -e "最优 IPv6 IP 为 ${BESTIP_IPV6}\n"
40 |
41 | [[ -f cloudflare.conf ]] && rm cloudflare.conf
42 |
43 | cat site.conf | while read domain
44 | do
45 | if [[ ${domain:0:1} != "#" && ${domain} != "" ]]; then
46 | echo "address=/${domain}/${BESTIP}" >> "cloudflare.conf"
47 | echo "address=/${domain}/${BESTIP_IPV6}" >> "cloudflare.conf"
48 | fi
49 | done
50 |
51 | [[ -f /etc/dnsmasq.d/cloudflare.conf ]] && rm /etc/dnsmasq.d/cloudflare.conf
52 | cp cloudflare.conf /etc/dnsmasq.d/cloudflare.conf
53 | systemctl restart dnsmasq.service
54 | }
55 |
56 | _UPDATE
--------------------------------------------------------------------------------
/script/cfst_dnspod.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # --------------------------------------------------------------
4 | # 项目: CloudflareSpeedTest 自动更新Dnspod优选解析
5 | # 版本: 1.0.0
6 | # 作者: imashen
7 | # --------------------------------------------------------------
8 |
9 | # 清理历史残留
10 | rm -f result4.csv result6.csv
11 | # DNSPod API 凭据
12 | dnspod_token="${API_TOKEN}"
13 | dnspod_domain="${DOMAIN}"
14 | dnspod_record="${SUB_DOMAIN}"
15 |
16 | # DNSPod API URL
17 | dnspod_api_url="https://dnsapi.cn"
18 |
19 | # 获取记录 ID
20 | get_record_id() {
21 | local record_type=$1
22 | local response
23 | response=$(curl -s -X POST -d "login_token=$dnspod_token&format=json&domain=$dnspod_domain&record_type=$record_type" "$dnspod_api_url/Record.List")
24 | local record_id
25 | record_id=$(echo "$response" | jq -r --arg type "$record_type" '.records[] | select(.type == $type) | .id')
26 | echo "$record_id"
27 | }
28 |
29 | # 创建 DNS 记录
30 | create_dns_record() {
31 | local record_type=$1
32 | local ip_address=$2
33 | local response
34 | response=$(curl -s -X POST -d "login_token=$dnspod_token&format=json&domain=$dnspod_domain&sub_domain=$dnspod_record&record_type=$record_type&record_line=默认&value=$ip_address" "$dnspod_api_url/Record.Create")
35 | local record_id
36 | record_id=$(echo "$response" | jq -r '.record.id')
37 | echo "$record_id"
38 | }
39 |
40 | # 更新 DNS 记录
41 | update_dns_record() {
42 | local record_id=$1
43 | local record_type=$2
44 | local ip_address=$3
45 | curl -s -X POST -d "login_token=$dnspod_token&format=json&domain=$dnspod_domain&record_id=$record_id&sub_domain=$dnspod_record&record_type=$record_type&record_line=默认&value=$ip_address" "$dnspod_api_url/Record.Modify"
46 | }
47 |
48 | # 运行 CloudflareST v4
49 | ./CloudflareST -f ip.txt -n 500 -o result4.csv
50 |
51 | # 读取 CSV 文件并提取优选 IPv4 地址
52 | preferred_ipv4=$(awk -F, 'NR==2 {print $1}' result4.csv)
53 |
54 | # 检查是否获取到了 IPv4 地址
55 | if [ -z "$preferred_ipv4" ]; then
56 | echo "Failed to get the preferred IPv4 address."
57 | else
58 | echo "BETTER IPv4: $preferred_ipv4"
59 |
60 | # 获取 IPv4 记录 ID
61 | ipv4_record_id=$(get_record_id "A")
62 |
63 | if [ -n "$ipv4_record_id" ]; then
64 | # 更新 IPv4 记录
65 | update_dns_record "$ipv4_record_id" "A" "$preferred_ipv4"
66 | echo "Updated DNSPod record with IPv4: $preferred_ipv4"
67 | else
68 | # 创建 IPv4 记录
69 | new_ipv4_record_id=$(create_dns_record "A" "$preferred_ipv4")
70 | if [ -n "$new_ipv4_record_id" ]; then
71 | echo "Created DNSPod record with IPv4: $preferred_ipv4"
72 | else
73 | echo "Failed to create DNSPod record with IPv4."
74 | fi
75 | fi
76 | fi
77 |
78 | # 运行 CloudflareST v6
79 | ./CloudflareST -f ipv6.txt -n 500 -o result6.csv
80 |
81 | # 读取 CSV 文件并提取优选 IPv6 地址
82 | preferred_ipv6=$(awk -F, 'NR==2 {print $1}' result6.csv)
83 |
84 | # 检查是否获取到了 IPv6 地址
85 | if [ -z "$preferred_ipv6" ]; then
86 | echo "Failed to get the preferred IPv6 address."
87 | else
88 | echo "BETTER IPv6: $preferred_ipv6"
89 |
90 | # 获取 IPv6 记录 ID
91 | ipv6_record_id=$(get_record_id "AAAA")
92 |
93 | if [ -n "$ipv6_record_id" ]; then
94 | # 更新 IPv6 记录
95 | update_dns_record "$ipv6_record_id" "AAAA" "$preferred_ipv6"
96 | echo "Updated DNSPod record with IPv6: $preferred_ipv6"
97 | else
98 | # 创建 IPv6 记录
99 | new_ipv6_record_id=$(create_dns_record "AAAA" "$preferred_ipv6")
100 | if [ -n "$new_ipv6_record_id" ]; then
101 | echo "Created DNSPod record with IPv6: $preferred_ipv6"
102 | else
103 | echo "Failed to create DNSPod record with IPv6."
104 | fi
105 | fi
106 | fi
107 |
--------------------------------------------------------------------------------
/script/cfst_hosts.bat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XIU2/CloudflareSpeedTest/04da9f56595fc7063a568f521e59f1b260cd308a/script/cfst_hosts.bat
--------------------------------------------------------------------------------
/script/cfst_hosts.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
3 | export PATH
4 | # --------------------------------------------------------------
5 | # 项目: CloudflareSpeedTest 自动更新 Hosts
6 | # 版本: 1.0.4
7 | # 作者: XIU2
8 | # 项目: https://github.com/XIU2/CloudflareSpeedTest
9 | # --------------------------------------------------------------
10 |
11 | _CHECK() {
12 | while true
13 | do
14 | if [[ ! -e "nowip_hosts.txt" ]]; then
15 | echo -e "该脚本的作用为 CloudflareST 测速后获取最快 IP 并替换 Hosts 中的 Cloudflare CDN IP。\n使用前请先阅读:https://github.com/XIU2/CloudflareSpeedTest/issues/42#issuecomment-768273848"
16 | echo -e "第一次使用,请先将 Hosts 中所有 Cloudflare CDN IP 统一改为一个 IP。"
17 | read -e -p "输入该 Cloudflare CDN IP 并回车(后续不再需要该步骤):" NOWIP
18 | if [[ ! -z "${NOWIP}" ]]; then
19 | echo ${NOWIP} > nowip_hosts.txt
20 | break
21 | else
22 | echo "该 IP 不能是空!"
23 | fi
24 | else
25 | break
26 | fi
27 | done
28 | }
29 |
30 | _UPDATE() {
31 | echo -e "开始测速..."
32 | NOWIP=$(head -1 nowip_hosts.txt)
33 |
34 | # 这里可以自己添加、修改 CloudflareST 的运行参数
35 | ./CloudflareST -o "result_hosts.txt"
36 |
37 | # 如果需要 "找不到满足条件的 IP 就一直循环测速下去",那么可以将下面的两个 exit 0 改为 _UPDATE 即可
38 | [[ ! -e "result_hosts.txt" ]] && echo "CloudflareST 测速结果 IP 数量为 0,跳过下面步骤..." && exit 0
39 |
40 | # 下面这行代码是 "找不到满足条件的 IP 就一直循环测速下去" 才需要的代码
41 | # 考虑到当指定了下载速度下限,但一个满足全部条件的 IP 都没找到时,CloudflareST 就会输出所有 IP 结果
42 | # 因此当你指定 -sl 参数时,需要移除下面这段代码开头的 # 井号注释符,来做文件行数判断(比如下载测速数量:10 个,那么下面的值就设在为 11)
43 | #[[ $(cat result_hosts.txt|wc -l) > 11 ]] && echo "CloudflareST 测速结果没有找到一个完全满足条件的 IP,重新测速..." && _UPDATE
44 |
45 |
46 | BESTIP=$(sed -n "2,1p" result_hosts.txt | awk -F, '{print $1}')
47 | if [[ -z "${BESTIP}" ]]; then
48 | echo "CloudflareST 测速结果 IP 数量为 0,跳过下面步骤..."
49 | exit 0
50 | fi
51 | echo ${BESTIP} > nowip_hosts.txt
52 | echo -e "\n旧 IP 为 ${NOWIP}\n新 IP 为 ${BESTIP}\n"
53 |
54 | echo "开始备份 Hosts 文件(hosts_backup)..."
55 | \cp -f /etc/hosts /etc/hosts_backup
56 |
57 | echo -e "开始替换..."
58 | sed -i 's/'${NOWIP}'/'${BESTIP}'/g' /etc/hosts
59 | echo -e "完成..."
60 | }
61 |
62 | _CHECK
63 | _UPDATE
--------------------------------------------------------------------------------
/script/cfst_hosts_mac.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
3 | export PATH
4 | # --------------------------------------------------------------
5 | # 项目: CloudflareSpeedTest 自动更新 Hosts
6 | # 版本: 1.0.4
7 | # 作者: XIU2
8 | # 项目: https://github.com/XIU2/CloudflareSpeedTest
9 | # --------------------------------------------------------------
10 |
11 | _CHECK() {
12 | while true
13 | do
14 | if [[ ! -e "nowip_hosts.txt" ]]; then
15 | echo -e "该脚本的作用为 CloudflareST 测速后获取最快 IP 并替换 Hosts 中的 Cloudflare CDN IP。\n使用前请先阅读:https://github.com/XIU2/CloudflareSpeedTest/issues/42#issuecomment-768273848"
16 | echo -e "第一次使用,请先将 Hosts 中所有 Cloudflare CDN IP 统一改为一个 IP。"
17 | read -e -p "输入该 Cloudflare CDN IP 并回车(后续不再需要该步骤):" NOWIP
18 | if [[ ! -z "${NOWIP}" ]]; then
19 | echo ${NOWIP} > nowip_hosts.txt
20 | break
21 | else
22 | echo "该 IP 不能是空!"
23 | fi
24 | else
25 | break
26 | fi
27 | done
28 | }
29 |
30 | _UPDATE() {
31 | echo -e "开始测速..."
32 | NOWIP=$(head -1 nowip_hosts.txt)
33 |
34 | # 这里可以自己添加、修改 CloudflareST 的运行参数
35 | ./CloudflareST -o "result_hosts.txt"
36 |
37 | # 如果需要 "找不到满足条件的 IP 就一直循环测速下去",那么可以将下面的两个 exit 0 改为 _UPDATE 即可
38 | [[ ! -e "result_hosts.txt" ]] && echo "CloudflareST 测速结果 IP 数量为 0,跳过下面步骤..." && exit 0
39 |
40 | # 下面这行代码是 "找不到满足条件的 IP 就一直循环测速下去" 才需要的代码
41 | # 考虑到当指定了下载速度下限,但一个满足全部条件的 IP 都没找到时,CloudflareST 就会输出所有 IP 结果
42 | # 因此当你指定 -sl 参数时,需要移除下面这段代码开头的 # 井号注释符,来做文件行数判断(比如下载测速数量:10 个,那么下面的值就设在为 11)
43 | #[[ $(cat result_hosts.txt|wc -l) > 11 ]] && echo "CloudflareST 测速结果没有找到一个完全满足条件的 IP,重新测速..." && _UPDATE
44 |
45 |
46 | BESTIP=$(sed -n "2,1p" result_hosts.txt | awk -F, '{print $1}')
47 | if [[ -z "${BESTIP}" ]]; then
48 | echo "CloudflareST 测速结果 IP 数量为 0,跳过下面步骤..."
49 | exit 0
50 | fi
51 | echo ${BESTIP} > nowip_hosts.txt
52 | echo -e "\n旧 IP 为 ${NOWIP}\n新 IP 为 ${BESTIP}\n"
53 |
54 | echo "开始备份 Hosts 文件(hosts_backup)..."
55 | \cp -f /etc/hosts /etc/hosts_backup
56 |
57 | echo -e "开始替换..."
58 | sed -i '' 's/'${NOWIP}'/'${BESTIP}'/g' /etc/hosts
59 | echo -e "完成..."
60 | }
61 |
62 | _CHECK
63 | _UPDATE
--------------------------------------------------------------------------------
/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/XIU2/CloudflareSpeedTest/utils"
14 |
15 | "github.com/VividCortex/ewma"
16 | )
17 |
18 | const (
19 | bufferSize = 1024
20 | defaultURL = "https://cf.xiu2.xyz/url"
21 | defaultTimeout = 10 * time.Second
22 | defaultDisableDownload = false
23 | defaultTestNum = 10
24 | defaultMinSpeed float64 = 0.0
25 | )
26 |
27 | var (
28 | URL = defaultURL
29 | Timeout = defaultTimeout
30 | Disable = defaultDisableDownload
31 |
32 | TestCount = defaultTestNum
33 | MinSpeed = defaultMinSpeed
34 | )
35 |
36 | func checkDownloadDefault() {
37 | if URL == "" {
38 | URL = defaultURL
39 | }
40 | if Timeout <= 0 {
41 | Timeout = defaultTimeout
42 | }
43 | if TestCount <= 0 {
44 | TestCount = defaultTestNum
45 | }
46 | if MinSpeed <= 0.0 {
47 | MinSpeed = defaultMinSpeed
48 | }
49 | }
50 |
51 | func TestDownloadSpeed(ipSet utils.PingDelaySet) (speedSet utils.DownloadSpeedSet) {
52 | checkDownloadDefault()
53 | if Disable {
54 | return utils.DownloadSpeedSet(ipSet)
55 | }
56 | if len(ipSet) <= 0 { // IP数组长度(IP数量) 大于 0 时才会继续下载测速
57 | fmt.Println("\n[信息] 延迟测速结果 IP 数量为 0,跳过下载测速。")
58 | return
59 | }
60 | testNum := TestCount
61 | if len(ipSet) < TestCount || MinSpeed > 0 { // 如果IP数组长度(IP数量) 小于下载测速数量(-dn),则次数修正为IP数
62 | testNum = len(ipSet)
63 | }
64 | if testNum < TestCount {
65 | TestCount = testNum
66 | }
67 |
68 | fmt.Printf("开始下载测速(下限:%.2f MB/s, 数量:%d, 队列:%d)\n", MinSpeed, TestCount, testNum)
69 | // 控制 下载测速进度条 与 延迟测速进度条 长度一致(强迫症)
70 | bar_a := len(strconv.Itoa(len(ipSet)))
71 | bar_b := " "
72 | for i := 0; i < bar_a; i++ {
73 | bar_b += " "
74 | }
75 | bar := utils.NewBar(TestCount, bar_b, "")
76 | for i := 0; i < testNum; i++ {
77 | speed := downloadHandler(ipSet[i].IP)
78 | ipSet[i].DownloadSpeed = speed
79 | // 在每个 IP 下载测速后,以 [下载速度下限] 条件过滤结果
80 | if speed >= MinSpeed*1024*1024 {
81 | bar.Grow(1, "")
82 | speedSet = append(speedSet, ipSet[i]) // 高于下载速度下限时,添加到新数组中
83 | if len(speedSet) == TestCount { // 凑够满足条件的 IP 时(下载测速数量 -dn),就跳出循环
84 | break
85 | }
86 | }
87 | }
88 | bar.Done()
89 | if len(speedSet) == 0 { // 没有符合速度限制的数据,返回所有测试数据
90 | speedSet = utils.DownloadSpeedSet(ipSet)
91 | }
92 | // 按速度排序
93 | sort.Sort(speedSet)
94 | return
95 | }
96 |
97 | func getDialContext(ip *net.IPAddr) func(ctx context.Context, network, address string) (net.Conn, error) {
98 | var fakeSourceAddr string
99 | if isIPv4(ip.String()) {
100 | fakeSourceAddr = fmt.Sprintf("%s:%d", ip.String(), TCPPort)
101 | } else {
102 | fakeSourceAddr = fmt.Sprintf("[%s]:%d", ip.String(), TCPPort)
103 | }
104 | return func(ctx context.Context, network, address string) (net.Conn, error) {
105 | return (&net.Dialer{}).DialContext(ctx, network, fakeSourceAddr)
106 | }
107 | }
108 |
109 | // return download Speed
110 | func downloadHandler(ip *net.IPAddr) float64 {
111 | client := &http.Client{
112 | Transport: &http.Transport{DialContext: getDialContext(ip)},
113 | Timeout: Timeout,
114 | CheckRedirect: func(req *http.Request, via []*http.Request) error {
115 | if len(via) > 10 { // 限制最多重定向 10 次
116 | return http.ErrUseLastResponse
117 | }
118 | if req.Header.Get("Referer") == defaultURL { // 当使用默认下载测速地址时,重定向不携带 Referer
119 | req.Header.Del("Referer")
120 | }
121 | return nil
122 | },
123 | }
124 | req, err := http.NewRequest("GET", URL, nil)
125 | if err != nil {
126 | return 0.0
127 | }
128 |
129 | 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")
130 |
131 | response, err := client.Do(req)
132 | if err != nil {
133 | return 0.0
134 | }
135 | defer response.Body.Close()
136 | if response.StatusCode != 200 {
137 | return 0.0
138 | }
139 | timeStart := time.Now() // 开始时间(当前)
140 | timeEnd := timeStart.Add(Timeout) // 加上下载测速时间得到的结束时间
141 |
142 | contentLength := response.ContentLength // 文件大小
143 | buffer := make([]byte, bufferSize)
144 |
145 | var (
146 | contentRead int64 = 0
147 | timeSlice = Timeout / 100
148 | timeCounter = 1
149 | lastContentRead int64 = 0
150 | )
151 |
152 | var nextTime = timeStart.Add(timeSlice * time.Duration(timeCounter))
153 | e := ewma.NewMovingAverage()
154 |
155 | // 循环计算,如果文件下载完了(两者相等),则退出循环(终止测速)
156 | for contentLength != contentRead {
157 | currentTime := time.Now()
158 | if currentTime.After(nextTime) {
159 | timeCounter++
160 | nextTime = timeStart.Add(timeSlice * time.Duration(timeCounter))
161 | e.Add(float64(contentRead - lastContentRead))
162 | lastContentRead = contentRead
163 | }
164 | // 如果超出下载测速时间,则退出循环(终止测速)
165 | if currentTime.After(timeEnd) {
166 | break
167 | }
168 | bufferRead, err := response.Body.Read(buffer)
169 | if err != nil {
170 | if err != io.EOF { // 如果文件下载过程中遇到报错(如 Timeout),且并不是因为文件下载完了,则退出循环(终止测速)
171 | break
172 | } else if contentLength == -1 { // 文件下载完成 且 文件大小未知,则退出循环(终止测速),例如:https://speed.cloudflare.com/__down?bytes=200000000 这样的,如果在 10 秒内就下载完成了,会导致测速结果明显偏低甚至显示为 0.00(下载速度太快时)
173 | break
174 | }
175 | // 获取上个时间片
176 | last_time_slice := timeStart.Add(timeSlice * time.Duration(timeCounter-1))
177 | // 下载数据量 / (用当前时间 - 上个时间片/ 时间片)
178 | e.Add(float64(contentRead-lastContentRead) / (float64(currentTime.Sub(last_time_slice)) / float64(timeSlice)))
179 | }
180 | contentRead += int64(bufferRead)
181 | }
182 | return e.Value() / (Timeout.Seconds() / 120)
183 | }
184 |
--------------------------------------------------------------------------------
/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}, // 跳过证书验证
31 | },
32 | CheckRedirect: func(req *http.Request, via []*http.Request) error {
33 | return http.ErrUseLastResponse // 阻止重定向
34 | },
35 | }
36 |
37 | // 先访问一次获得 HTTP 状态码 及 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 | // 如果未指定的 HTTP 状态码,或指定的状态码不合规,则默认只认为 200、301、302 才算 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 | // 只有指定了地区才匹配机场三字码
65 | if HttpingCFColo != "" {
66 | // 通过头部 Server 值判断是 Cloudflare 还是 AWS CloudFront 并设置 cfRay 为各自的机场三字码完整内容
67 | cfRay := func() string {
68 | if resp.Header.Get("Server") == "cloudflare" {
69 | return resp.Header.Get("CF-RAY") // 示例 cf-ray: 7bd32409eda7b020-SJC
70 | }
71 | return resp.Header.Get("x-amz-cf-pop") // 示例 X-Amz-Cf-Pop: SIN52-P1
72 | }()
73 | colo := p.getColo(cfRay)
74 | if colo == "" { // 没有匹配到三字码或不符合指定地区则直接结束该 IP 测试
75 | return 0, 0
76 | }
77 | }
78 |
79 | }
80 |
81 | // 循环测速计算延迟
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("意外的错误,情报告:", 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 | // 将参数指定的地区三字码转为大写并格式化
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 | // 正则匹配并返回 机场三字码
129 | out := OutRegexp.FindString(b)
130 |
131 | if HttpingCFColomap == nil {
132 | return out
133 | }
134 | // 匹配 机场三字码 是否为指定的地区
135 | _, ok := HttpingCFColomap.Load(out)
136 | if ok {
137 | return out
138 | }
139 |
140 | return ""
141 | }
142 |
--------------------------------------------------------------------------------
/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 test all ip
18 | TestAll = false
19 | // IPFile is the filename of IP Rangs
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 { // 对于 /32 这种单独的 IP
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 | // 如果是单独 IP 则加上子网掩码,反之则获取子网掩码(r.mask)
53 | func (r *IPRanges) fixIP(ip string) string {
54 | // 如果不含有 '/' 则代表不是 IP 段,而是一个单独的 IP,因此需要加上 /32 /128 子网掩码
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 | // 解析 IP 段,获得 IP、IP 范围、子网掩码
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 err", 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 | // 返回第四段 ip 的最小值及可用数目
85 | func (r *IPRanges) getIPRange() (minIP, hosts byte) {
86 | minIP = r.firstIP[15] & r.ipNet.Mask[3] // IP 第四段最小值
87 |
88 | // 根据子网掩码获取主机数量
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) // 总可用 IP 数
94 | if total > 255 { // 矫正 第四段 可用 IP 数
95 | hosts = 255
96 | return
97 | }
98 | hosts = byte(total)
99 | return
100 | }
101 |
102 | func (r *IPRanges) chooseIPv4() {
103 | if r.mask == "/32" { // 单个 IP 则无需随机,直接加入自身即可
104 | r.appendIP(r.firstIP)
105 | } else {
106 | minIP, hosts := r.getIPRange() // 返回第四段 IP 的最小值及可用数目
107 | for r.ipNet.Contains(r.firstIP) { // 只要该 IP 没有超出 IP 网段范围,就继续循环随机
108 | if TestAll { // 如果是测速全部 IP
109 | for i := 0; i <= int(hosts); i++ { // 遍历 IP 最后一段最小值到最大值
110 | r.appendIPv4(byte(i) + minIP)
111 | }
112 | } else { // 随机 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" { // 单个 IP 则无需随机,直接加入自身即可
128 | r.appendIP(r.firstIP)
129 | } else {
130 | var tempIP uint8 // 临时变量,用于记录前一位的值
131 | for r.ipNet.Contains(r.firstIP) { // 只要该 IP 没有超出 IP 网段范围,就继续循环随机
132 | r.firstIP[15] = randIPEndWith(255) // 随机 IP 的最后一段
133 | r.firstIP[14] = randIPEndWith(255) // 随机 IP 的最后一段
134 |
135 | targetIP := make([]byte, len(r.firstIP))
136 | copy(targetIP, r.firstIP)
137 | r.appendIP(targetIP) // 加入 IP 地址池
138 |
139 | for i := 13; i >= 0; i-- { // 从倒数第三位开始往前随机
140 | tempIP = r.firstIP[i] // 保存前一位的值
141 | r.firstIP[i] += randIPEndWith(255) // 随机 0~255,加到当前位上
142 | if r.firstIP[i] >= tempIP { // 如果当前位的值大于等于前一位的值,说明随机成功了,可以退出该循环
143 | break
144 | }
145 | }
146 | }
147 | }
148 | }
149 |
150 | func loadIPRanges() []*net.IPAddr {
151 | ranges := newIPRanges()
152 | if IPText != "" { // 从参数中获取 IP 段数据
153 | IPs := strings.Split(IPText, ",") // 以逗号分隔为数组并循环遍历
154 | for _, IP := range IPs {
155 | IP = strings.TrimSpace(IP) // 去除首尾的空白字符(空格、制表符、换行符等)
156 | if IP == "" { // 跳过空的(即开头、结尾或连续多个 ,, 的情况)
157 | continue
158 | }
159 | ranges.parseCIDR(IP) // 解析 IP 段,获得 IP、IP 范围、子网掩码
160 | if isIPv4(IP) { // 生成要测速的所有 IPv4 / IPv6 地址(单个/随机/全部)
161 | ranges.chooseIPv4()
162 | } else {
163 | ranges.chooseIPv6()
164 | }
165 | }
166 | } else { // 从文件中获取 IP 段数据
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() { // 循环遍历文件每一行
177 | line := strings.TrimSpace(scanner.Text()) // 去除首尾的空白字符(空格、制表符、换行符等)
178 | if line == "" { // 跳过空行
179 | continue
180 | }
181 | ranges.parseCIDR(line) // 解析 IP 段,获得 IP、IP 范围、子网掩码
182 | if isIPv4(line) { // 生成要测速的所有 IPv4 / IPv6 地址(单个/随机/全部)
183 | ranges.chooseIPv4()
184 | } else {
185 | ranges.chooseIPv6()
186 | }
187 | }
188 | }
189 | return ranges.ips
190 | }
191 |
--------------------------------------------------------------------------------
/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/XIU2/CloudflareSpeedTest/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), "可用:", ""),
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("开始延迟测速(模式:HTTP, 端口:%d, 范围:%v ~ %v ms, 丢包:%.2f)\n", TCPPort, utils.InputMinDelay.Milliseconds(), utils.InputMaxDelay.Milliseconds(), utils.InputMaxLossRate)
68 | } else {
69 | fmt.Printf("开始延迟测速(模式:TCP, 端口:%d, 范围:%v ~ %v ms, 丢包:%.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 |
--------------------------------------------------------------------------------
/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 | // 是否打印测试结果
29 | func NoPrintResult() bool {
30 | return PrintNum == 0
31 | }
32 |
33 | // 是否输出到文件
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 | // 计算丢包率
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("创建文件[%s]失败:%v", Output, err)
78 | return
79 | }
80 | defer fp.Close()
81 | w := csv.NewWriter(fp) //创建一个新的写入文件流
82 | _ = w.Write([]string{"IP 地址", "已发送", "已接收", "丢包率", "平均延迟", "下载速度 (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 | // 延迟丢包排序
96 | type PingDelaySet []CloudflareIPData
97 |
98 | // 延迟条件过滤
99 | func (s PingDelaySet) FilterDelay() (data PingDelaySet) {
100 | if InputMaxDelay > maxDelay || InputMinDelay < minDelay { // 当输入的延迟条件不在默认范围内时,不进行过滤
101 | return s
102 | }
103 | if InputMaxDelay == maxDelay && InputMinDelay == minDelay { // 当输入的延迟条件为默认值时,不进行过滤
104 | return s
105 | }
106 | for _, v := range s {
107 | if v.Delay > InputMaxDelay { // 平均延迟上限,延迟大于条件最大值时,后面的数据都不满足条件,直接跳出循环
108 | break
109 | }
110 | if v.Delay < InputMinDelay { // 平均延迟下限,延迟小于条件最小值时,不满足条件,跳过
111 | continue
112 | }
113 | data = append(data, v) // 延迟满足条件时,添加到新数组中
114 | }
115 | return
116 | }
117 |
118 | // 丢包条件过滤
119 | func (s PingDelaySet) FilterLossRate() (data PingDelaySet) {
120 | if InputMaxLossRate >= maxLossRate { // 当输入的丢包条件为默认值时,不进行过滤
121 | return s
122 | }
123 | for _, v := range s {
124 | if v.getLossRate() > InputMaxLossRate { // 丢包几率上限
125 | break
126 | }
127 | data = append(data, v) // 丢包率满足条件时,添加到新数组中
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 | // 下载速度排序
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 { // IP数组长度(IP数量) 大于 0 时继续
164 | fmt.Println("\n[信息] 完整测速结果 IP 数量为 0,跳过输出结果。")
165 | return
166 | }
167 | dateString := convertToString(s) // 转为多维数组 [][]String
168 | if len(dateString) < PrintNum { // 如果IP数组长度(IP数量) 小于 打印次数,则次数改为IP数量
169 | PrintNum = len(dateString)
170 | }
171 | headFormat := "%-16s%-5s%-5s%-5s%-6s%-11s\n"
172 | dataFormat := "%-18s%-8s%-8s%-8s%-10s%-15s\n"
173 | for i := 0; i < PrintNum; i++ { // 如果要输出的 IP 中包含 IPv6,那么就需要调整一下间隔
174 | if len(dateString[i][0]) > 15 {
175 | headFormat = "%-40s%-5s%-5s%-5s%-6s%-11s\n"
176 | dataFormat = "%-42s%-8s%-8s%-8s%-10s%-15s\n"
177 | break
178 | }
179 | }
180 | fmt.Printf(headFormat, "IP 地址", "已发送", "已接收", "丢包率", "平均延迟", "下载速度 (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("\n完整测速结果已写入 %v 文件,可使用记事本/表格软件查看。\n", Output)
186 | }
187 | }
188 |
--------------------------------------------------------------------------------
/utils/progress.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/cheggaaa/pb/v3"
7 | )
8 |
9 | type Bar struct {
10 | pb *pb.ProgressBar
11 | }
12 |
13 | func NewBar(count int, MyStrStart, MyStrEnd string) *Bar {
14 | tmpl := fmt.Sprintf(`{{counters . }} {{ bar . "[" "-" (cycle . "↖" "↗" "↘" "↙" ) "_" "]"}} %s {{string . "MyStr" | green}} %s `, MyStrStart, MyStrEnd)
15 | bar := pb.ProgressBarTemplate(tmpl).Start(count)
16 | return &Bar{pb: bar}
17 | }
18 |
19 | func (b *Bar) Grow(num int, MyStrVal string) {
20 | b.pb.Set("MyStr", MyStrVal).Add(num)
21 | }
22 |
23 | func (b *Bar) Done() {
24 | b.pb.Finish()
25 | }
26 |
--------------------------------------------------------------------------------