Skip to content

Commit

Permalink
调整测速逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
sinspired committed Jul 20, 2024
1 parent 51351c7 commit c44eb9d
Show file tree
Hide file tree
Showing 7 changed files with 470 additions and 184 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/sinspired/CloudflareBestIP
go 1.22.4

require (
github.com/VividCortex/ewma v1.2.0
github.com/mattn/go-ieproxy v0.0.12
golang.org/x/sys v0.22.0
golang.org/x/text v0.16.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
github.com/VividCortex/ewma v1.2.0 h1:f58SaIzcDXrSy3kWaHNvuJgJ3Nmz59Zji6XoJR/q1ow=
github.com/VividCortex/ewma v1.2.0/go.mod h1:nz4BbCtbLyFDeC9SUHbtcT5644juEuWfUAUnGx7j5l4=
github.com/mattn/go-ieproxy v0.0.12 h1:OZkUFJC3ESNZPQ+6LzC3VJIFSnreeFLQyqvBWtvfL2M=
github.com/mattn/go-ieproxy v0.0.12/go.mod h1:Vn+N61199DAnVeTgaF8eoB9PvLO8P3OBnG95ENh7B7c=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
Expand Down
509 changes: 348 additions & 161 deletions main.go

Large diffs are not rendered by default.

13 changes: 11 additions & 2 deletions mergeCSV.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"io"
"os"
"path/filepath"
"strings"
)

func main() {
Expand All @@ -17,16 +18,24 @@ func main() {

// 检查是否提供了文件夹路径
if len(args) < 1 {
fmt.Println("请提供文件夹路径(相对路径或绝对路径),例如:go run mergeCSV.go folderpath")
fmt.Println("请提供文件夹路径(相对路径或绝对路径)和结果文件名,例如:go run mergeCSV.go folderpath mergedTxtFile")
return
}

// 文件夹路径
folderPath := args[0]
mergedTxtFile := args[1]
if mergedTxtFile == "" {
if strings.Contains(folderPath, "ipscanner") {
mergedTxtFile = "ip_Scanner.txt"
} else {
mergedTxtFile = "ip_Merged.txt"
}
}

// 创建一个新的 TXT 文件来存储结果
// https://codeload.github.com/ip-scanner/cloudflare/zip/refs/heads/main
outputFile, err := os.Create("ip_Scanner.txt")
outputFile, err := os.Create(mergedTxtFile)
if err != nil {
fmt.Println("无法创建输出文件:", err)
return
Expand Down
53 changes: 47 additions & 6 deletions processCIDR.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package main

import (
"bufio" // 用于读取文件
// "flag"
"fmt"

// "fmt"
"log" // 用于日志记录
"math/rand" // 用于生成随机数
Expand All @@ -11,13 +14,16 @@ import (
"time" // 用于时间相关操作
)

const defaultInputFile = "ip.txt"
const (
defaultInputFile = "ip_CFv4IPDB.txt"
defaultOutputFile = "ip_CFv4IPDB_Parsed.txt"
)

var (
// TestAll 表示是否测试所有IP
TestAll = false
// IPFile 是包含IP范围的文件名
IPFile = defaultInputFile
IPFile string
IPText string
)

Expand Down Expand Up @@ -155,7 +161,7 @@ func (r *IPRanges) chooseIPv6() {
}

// loadIPRanges 从文件或字符串中加载IP范围
func loadIPRanges() []*net.IPAddr {
func loadIPRanges(IPFile string) []*net.IPAddr {
ranges := newIPRanges()
if IPText != "" { // 从参数中获取IP段数据
IPs := strings.Split(IPText, ",")
Expand Down Expand Up @@ -197,11 +203,14 @@ func loadIPRanges() []*net.IPAddr {
return ranges.ips
}

func main() {
ips := loadIPRanges() // 获取IP列表
func randomParseCIDR(IPFile string, parsedIPFile string) {
ips := loadIPRanges(IPFile) // 获取IP列表
if parsedIPFile == "" {
parsedIPFile = defaultOutputFile
}

// 创建文件
file, err := os.Create("ip_CFip.txt")
file, err := os.Create(parsedIPFile)
if err != nil {
log.Fatal(err)
}
Expand All @@ -215,4 +224,36 @@ func main() {
log.Fatal(err)
}
}
fmt.Printf("\033[90mCIDR地址 %s 已解析并随机主机名,保存为 %s。\n如未取得优选结果,可修改参数并再次解析。\033[0m\n", IPFile, parsedIPFile)
}

// func main() {
// // 定义命令行参数
// flag.Parse()
// args := flag.Args()

// // 检查是否提供了文件路径
// if len(args) < 1 {
// fmt.Println("请提供文件路径(相对路径或绝对路径)和解析结果文件名(如留空会自动生成)")
// return
// }

// // 文件路径
// IPFile := args[0]
// parsedIPFile := args[1]
// if IPFile == "" {
// IPFile = defaultInputFile
// }
// if parsedIPFile != "" {
// pasedName := strings.Split(parsedIPFile, ".")[0]
// parts := strings.Split(pasedName, "_")
// if len(parts) > 1 && parts[1] != "" {
// parsedIPFile = parts[1] + "_Pased.txt"
// } else {
// parsedIPFile = pasedName + "_Pased.txt"
// }

// }

// randomParseCIDR(IPFile, parsedIPFile)
// }
36 changes: 31 additions & 5 deletions processFofaCSV.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"archive/zip"
"bufio"
"encoding/csv"
"fmt"
"io"
Expand Down Expand Up @@ -111,7 +112,6 @@ func processCSV(filePath, outputFolder string, zipFiles *[]string) {
}
cleanIPs := []string{}
for i, ip := range ips {

if !strings.Contains(orgs[i], "Alibaba") && !strings.Contains(orgs[i], "Cloudflare") {
cleanIPs = append(cleanIPs, ip)
}
Expand All @@ -135,7 +135,7 @@ func processCSV(filePath, outputFolder string, zipFiles *[]string) {
} else {
httpIPs, httpsIPs := []string{}, []string{}
for i, ip := range ips {
if !strings.Contains(orgs[i], "Alibaba") && !strings.Contains(orgs[i], "Cloudflare") {
if !strings.Contains(orgs[i], "Alibaba") && !strings.Contains(orgs[i], "Cloudflare") && ip != "" {
if protocols[i] == "http" {
httpIPs = append(httpIPs, fmt.Sprintf("%s:%s", ip, ports[i]))
} else {
Expand Down Expand Up @@ -170,14 +170,40 @@ func unique(slice []string) []string {
}

func writeToFile(filePath string, data []string) {
file, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
// 创建一个 map 用于存储唯一的行
lines := make(map[string]struct{})

// 如果文件存在,读取现有文件内容
file, err := os.OpenFile(filePath, os.O_RDONLY, 0o644)
if err == nil {
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text()) // 去除行首尾的空白字符
if line != "" { // 过滤空行
lines[line] = struct{}{}
}
}
file.Close() // 关闭文件
}

// 将新数据添加到 map 中
for _, line := range data {
line = strings.TrimSpace(line) // 去除行首尾的空白字符
if line != "" { // 过滤空行
lines[line] = struct{}{}
}
}

// 以写模式打开文件(清空文件内容)
file, err = os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
if err != nil {
fmt.Println("写入文件错误:", err)
return
}
defer file.Close()
defer file.Close() // 函数结束前关闭文件

for _, line := range data {
// 将唯一的行写入文件
for line := range lines {
_, err := file.WriteString(line + "\n")
if err != nil {
fmt.Println("写入文件错误:", err)
Expand Down
40 changes: 30 additions & 10 deletions update.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
)

// func main() {
// dataUpdate("result_test.csv")
// dataUpdate("result_test.csv", "example.com", "your_token")
// }

// 移除BOM(字节顺序标记)
Expand All @@ -24,6 +24,22 @@ func removeBOM(data []byte) []byte {
return data
}

// 发送HTTP GET请求并处理重试逻辑
func sendGetRequest(client *http.Client, urlStr string, maxRetries int) (*http.Response, error) {
var resp *http.Response
var err error
for i := 0; i < maxRetries; i++ {
resp, err = client.Get(urlStr)
if err == nil {
return resp, nil
}
// fmt.Printf("请求失败(重试 %d/%d 次):%v\n", i+1, maxRetries, err)
fmt.Printf("请求失败(重试 %d/%d 次)\n", i+1, maxRetries)
time.Sleep(1 * time.Second) // 等待2秒后重试
}
return nil, err
}

// 更新数据
func dataUpdate(fileName string, domain string, token string) {
// 清除输出内容
Expand Down Expand Up @@ -55,17 +71,24 @@ func dataUpdate(fileName string, domain string, token string) {
// 构造更新URL
updateUrlStr := fmt.Sprintf("https://%s/%s?token=%s&b64=%s&v=%d", domain, url.PathEscape(fileName), token, url.QueryEscape(base64Text), time.Now().Unix())

// 设置超时
// 设置HTTP客户端,启用Keep-Alive和重试逻辑
client := &http.Client{
Timeout: time.Second * 230, // 设置超时时间为30秒
Transport: &http.Transport{
MaxIdleConns: 10, // 最大空闲连接数
IdleConnTimeout: 30 * time.Second, // 空闲连接的超时时间
MaxIdleConnsPerHost: 2, // 每个主机的最大空闲连接数
DisableKeepAlives: false, // 启用 Keep-Alive
// TLSHandshakeTimeout: 10 * time.Second,
},
Timeout: time.Second * 30, // 设置单次请求超时时间为30秒
}

// 发送更新请求
resp, err := client.Get(updateUrlStr)
resp, err := sendGetRequest(client, updateUrlStr, 5) // 尝试重试5次
if err != nil {
fmt.Printf("发送更新请求时出错,请手动上传文件或重新执行程序!\n %v\n", err)
fmt.Printf("自动更新失败,请手动上传文件或重新执行程序!\n %v\n", err)
return
}

defer resp.Body.Close()

// 检查更新请求的状态码
Expand All @@ -75,14 +98,11 @@ func dataUpdate(fileName string, domain string, token string) {
}
fmt.Println("发起数据更新请求...........................................[\033[32mok\033[0m]")

// 等待一段时间以确保服务器处理更新请求
// time.Sleep(2 * time.Second)

// 构造读取URL
readUrlStr := fmt.Sprintf("https://%s/%s?token=%s&v=%d", domain, url.PathEscape(fileName), token, time.Now().Unix())

// 发送读取请求
resp, err = http.Get(readUrlStr)
resp, err = sendGetRequest(client, readUrlStr, 5) // 尝试重试5次
if err != nil {
fmt.Printf("发送读取请求时出错: %v\n", err)
return
Expand Down

0 comments on commit c44eb9d

Please sign in to comment.