fixed address resolution #619

Merged
tech merged 1 commits from tron-616 into main 2026-03-03 18:37:32 +00:00

View File

@@ -52,7 +52,11 @@ func NewClient(grpcURL string, timeout time.Duration, authToken string, forceIPv
opts := []grpc.DialOption{transportCreds} opts := []grpc.DialOption{transportCreds}
if forceIPv4 { if forceIPv4 {
opts = append(opts, grpc.WithContextDialer(grpcForceIPv4Dialer)) host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, merrors.InvalidArgument("tronclient: invalid grpc address: " + address)
}
opts = append(opts, grpc.WithContextDialer(newForceIPv4Dialer(host, port)))
} }
if token := strings.TrimSpace(authToken); token != "" { if token := strings.TrimSpace(authToken); token != "" {
opts = append(opts, opts = append(opts,
@@ -71,37 +75,34 @@ func NewClient(grpcURL string, timeout time.Duration, authToken string, forceIPv
}, nil }, nil
} }
func grpcForceIPv4Dialer(ctx context.Context, address string) (net.Conn, error) { func newForceIPv4Dialer(host, port string) func(context.Context, string) (net.Conn, error) {
host, port, err := net.SplitHostPort(address) return func(ctx context.Context, _ string) (net.Conn, error) {
if err != nil { ips, err := net.DefaultResolver.LookupIP(ctx, "ip4", host)
return nil, err if err != nil {
} return nil, err
ips, err := net.DefaultResolver.LookupIP(ctx, "ip4", host)
if err != nil {
return nil, err
}
if len(ips) == 0 {
return nil, merrors.Internal(fmt.Sprintf("no IPv4 address found for %s", host))
}
var dialer net.Dialer
var lastErr error
for _, ip := range ips {
target := net.JoinHostPort(ip.String(), port)
conn, err := dialer.DialContext(ctx, "tcp4", target)
if err == nil {
return conn, nil
} }
lastErr = err if len(ips) == 0 {
if ctx.Err() != nil { return nil, merrors.Internal(fmt.Sprintf("no IPv4 address found for %s", host))
break
} }
var dialer net.Dialer
var lastErr error
for _, ip := range ips {
target := net.JoinHostPort(ip.String(), port)
conn, err := dialer.DialContext(ctx, "tcp4", target)
if err == nil {
return conn, nil
}
lastErr = err
if ctx.Err() != nil {
break
}
}
if lastErr != nil {
return nil, merrors.Internal(fmt.Sprintf("failed to dial any IPv4 address for %s: %v", host, lastErr))
}
return nil, merrors.Internal(fmt.Sprintf("failed to dial IPv4 address for %s", host))
} }
if lastErr != nil {
return nil, merrors.Internal(fmt.Sprintf("failed to dial any IPv4 address for %s: %v", host, lastErr))
}
return nil, merrors.Internal(fmt.Sprintf("failed to dial IPv4 address for %s", host))
} }
func normalizeGRPCAddress(grpcURL string) (string, bool, error) { func normalizeGRPCAddress(grpcURL string) (string, bool, error) {