This repository has been archived by the owner on Nov 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
要提交的变更: 修改: wshandle/client.go 新文件: wshandle/latency.go
- Loading branch information
1 parent
c8da767
commit 1cf4fc4
Showing
2 changed files
with
129 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
package wshandle | ||
|
||
import ( | ||
"fmt" | ||
"log" | ||
"net" | ||
"strings" | ||
"time" | ||
|
||
"github.com/fatih/color" | ||
) | ||
|
||
var ( | ||
result string | ||
results = make(chan string) | ||
) | ||
|
||
func GetFastIP(domain string, port string) string { | ||
|
||
ips, err := net.LookupIP(domain) | ||
if err != nil { | ||
log.Fatal("DNS 解析失败,请检查您的系统 DNS 设置") | ||
return "" | ||
} | ||
|
||
for _, ip := range ips { | ||
go checkLatency(ip.String(), port) | ||
} | ||
|
||
select { | ||
case result = <-results: | ||
case <-time.After(1 * time.Second): | ||
|
||
} | ||
if result == "" { | ||
log.Fatal("IP 连接均超时,请检查您的网络") | ||
} | ||
res := strings.Split(result, "-") | ||
|
||
if len(ips) > 1 { | ||
_, _ = fmt.Fprintf(color.Output, "%s 已为您优选最近的节点 %s - %s\n", | ||
color.New(color.FgWhite, color.Bold).Sprintf("[NextTrace API]"), | ||
color.New(color.FgGreen, color.Bold).Sprintf("%s", res[0]), | ||
color.New(color.FgCyan, color.Bold).Sprintf("%sms", res[1]), | ||
) | ||
} | ||
|
||
return res[0] | ||
} | ||
|
||
func checkLatency(ip string, port string) { | ||
start := time.Now() | ||
if !strings.Contains(ip, ".") { | ||
ip = "[" + ip + "]" | ||
} | ||
conn, err := net.DialTimeout("tcp", ip+":"+port, time.Second*1) | ||
if err != nil { | ||
return | ||
} | ||
defer func(conn net.Conn) { | ||
err := conn.Close() | ||
if err != nil { | ||
return | ||
} | ||
}(conn) | ||
if result == "" { | ||
result = fmt.Sprintf("%s-%.2f", ip, float64(time.Since(start))/float64(time.Millisecond)) | ||
results <- result | ||
return | ||
} | ||
} |