Skip to content

Commit

Permalink
fix: tcp-ping
Browse files Browse the repository at this point in the history
  • Loading branch information
naiba committed Jul 28, 2024
1 parent c50a21c commit fa0cc9b
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 5 deletions.
12 changes: 10 additions & 2 deletions cmd/agent/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -474,13 +474,21 @@ func handleUpgradeTask(*pb.Task, *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 {
result.Data = err.Error()
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()
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 {
conn.Write([]byte("ping\n"))
conn.Close()
Expand Down
15 changes: 15 additions & 0 deletions cmd/agent/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"net"
"reflect"
"testing"
)
Expand Down Expand Up @@ -31,4 +32,18 @@ func TestLookupIP(t *testing.T) {
if err != nil {
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)
}
}
9 changes: 6 additions & 3 deletions pkg/monitor/myip.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,17 @@ func UpdateIP(useIPv6CountryCode bool, period uint32) {
continue
}
if ipv4 == "" || ipv6 == "" {
if ipv4 == "" {
GeoQueryIP = ipv6
} else {
GeoQueryIP = ipv4
}
CachedIP = fmt.Sprintf("%s%s", ipv4, ipv6)
} else {
CachedIP = fmt.Sprintf("%s/%s", ipv4, ipv6)
}

if !useIPv6CountryCode {
GeoQueryIP = ipv4
} else {
if useIPv6CountryCode {
GeoQueryIP = ipv6
}

Expand Down

0 comments on commit fa0cc9b

Please sign in to comment.