forked from things-go/go-socks5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolver.go
45 lines (38 loc) · 1.01 KB
/
resolver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package socks5
import (
"context"
"net"
)
func NewSocksResolver(r *net.Resolver) NameResolver {
if r == nil {
return DNSResolver{}
}
return socksResolver{r}
}
type socksResolver struct {
*net.Resolver
}
func (sr socksResolver) Resolve(ctx context.Context, name string) (context.Context, net.IP, error) {
ips, err := sr.Resolver.LookupIPAddr(ctx, name)
if err != nil {
return ctx, nil, err
}
if len(ips) == 0 {
return ctx, nil, &net.DNSError{Err: "no such host", Name: name}
}
return ctx, ips[0].IP, nil
}
// NameResolver is used to implement custom name resolution
type NameResolver interface {
Resolve(ctx context.Context, name string) (context.Context, net.IP, error)
}
// DNSResolver uses the system DNS to resolve host names
type DNSResolver struct{}
// Resolve implement interface NameResolver
func (d DNSResolver) Resolve(ctx context.Context, name string) (context.Context, net.IP, error) {
addr, err := net.ResolveIPAddr("ip", name)
if err != nil {
return ctx, nil, err
}
return ctx, addr.IP, err
}