refactor: ping if-flow and remove timeout

This commit is contained in:
yusing 2025-04-17 14:21:47 +08:00
parent cfd1d8fff0
commit c7e0dcbfd8

View file

@ -94,24 +94,20 @@ func Ping(ctx context.Context, ip net.IP) (bool, error) {
} }
} }
var pingDialer = &net.Dialer{
Timeout: 2 * time.Second,
}
// PingWithTCPFallback pings the IP address using ICMP and TCP fallback. // PingWithTCPFallback pings the IP address using ICMP and TCP fallback.
// //
// If the ICMP ping fails due to permission error, it will try to connect to the specified port. // If the ICMP ping fails due to permission error, it will try to connect to the specified port.
func PingWithTCPFallback(ctx context.Context, ip net.IP, port int) (bool, error) { func PingWithTCPFallback(ctx context.Context, ip net.IP, port int) (bool, error) {
ok, err := Ping(ctx, ip) ok, err := Ping(ctx, ip)
if err != nil { if err == nil {
return ok, nil
}
if !errors.Is(err, os.ErrPermission) { if !errors.Is(err, os.ErrPermission) {
return false, err return false, err
} }
} else {
return ok, nil
}
conn, err := pingDialer.DialContext(ctx, "tcp", fmt.Sprintf("%s:%d", ip, port)) var dialer net.Dialer
conn, err := dialer.DialContext(ctx, "tcp", fmt.Sprintf("%s:%d", ip, port))
if err != nil { if err != nil {
return false, err return false, err
} }