fix: tcp-ping

This commit is contained in:
naiba 2024-07-28 18:48:44 +08:00
parent c50a21c5b1
commit fa0cc9bb7a
3 changed files with 31 additions and 5 deletions

View File

@ -474,13 +474,21 @@ func handleUpgradeTask(*pb.Task, *pb.TaskResult) {
} }
func handleTcpPingTask(task *pb.Task, result *pb.TaskResult) { func handleTcpPingTask(task *pb.Task, result *pb.TaskResult) {
ipAddr, err := lookupIP(task.GetData()) host, port, err := net.SplitHostPort(task.GetData())
if err != nil { if err != nil {
result.Data = err.Error() result.Data = err.Error()
return return
} }
ipAddr, err := lookupIP(host)
if err != nil {
result.Data = err.Error()
return
}
if strings.Contains(ipAddr, ":") {
ipAddr = fmt.Sprintf("[%s]", ipAddr)
}
start := time.Now() start := time.Now()
conn, err := net.DialTimeout("tcp", ipAddr, time.Second*10) conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%s", ipAddr, port), time.Second*10)
if err == nil { if err == nil {
conn.Write([]byte("ping\n")) conn.Write([]byte("ping\n"))
conn.Close() conn.Close()

View File

@ -2,6 +2,7 @@ package main
import ( import (
"fmt" "fmt"
"net"
"reflect" "reflect"
"testing" "testing"
) )
@ -31,4 +32,18 @@ func TestLookupIP(t *testing.T) {
if err != nil { if err != nil {
t.Errorf("lookupIP failed: %v", err) t.Errorf("lookupIP failed: %v", err)
} }
_, err = net.ResolveIPAddr("ip", "www.google.com")
if err != nil {
t.Errorf("ResolveIPAddr failed: %v", err)
}
ip, err = lookupIP("ipv6.google.com")
fmt.Printf("ip: %v, err: %v\n", ip, err)
if err != nil {
t.Errorf("lookupIP failed: %v", err)
}
_, err = net.ResolveIPAddr("ip", "ipv6.google.com")
if err != nil {
t.Errorf("ResolveIPAddr failed: %v", err)
}
} }

View File

@ -39,14 +39,17 @@ func UpdateIP(useIPv6CountryCode bool, period uint32) {
continue continue
} }
if ipv4 == "" || ipv6 == "" { if ipv4 == "" || ipv6 == "" {
if ipv4 == "" {
GeoQueryIP = ipv6
} else {
GeoQueryIP = ipv4
}
CachedIP = fmt.Sprintf("%s%s", ipv4, ipv6) CachedIP = fmt.Sprintf("%s%s", ipv4, ipv6)
} else { } else {
CachedIP = fmt.Sprintf("%s/%s", ipv4, ipv6) CachedIP = fmt.Sprintf("%s/%s", ipv4, ipv6)
} }
if !useIPv6CountryCode { if useIPv6CountryCode {
GeoQueryIP = ipv4
} else {
GeoQueryIP = ipv6 GeoQueryIP = ipv6
} }