MCPcopy
hub / github.com/karol-broda/snitch / ResolveAddr

Method ResolveAddr

internal/resolver/resolver.go:38–84  ·  view source on GitHub ↗

ResolveAddr resolves an IP address to a hostname, with caching

(addr string)

Source from the content-addressed store, hash-verified

36
37// ResolveAddr resolves an IP address to a hostname, with caching
38func (r *Resolver) ResolveAddr(addr string) string {
39 // check cache first (unless caching is disabled)
40 if !r.noCache {
41 r.mutex.RLock()
42 if cached, exists := r.cache[addr]; exists {
43 r.mutex.RUnlock()
44 return cached
45 }
46 r.mutex.RUnlock()
47 }
48
49 // parse ip to validate it
50 ip := net.ParseIP(addr)
51 if ip == nil {
52 return addr
53 }
54
55 // perform resolution with timeout
56 start := time.Now()
57 ctx, cancel := context.WithTimeout(context.Background(), r.timeout)
58 defer cancel()
59
60 names, err := net.DefaultResolver.LookupAddr(ctx, addr)
61
62 resolved := addr
63 if err == nil && len(names) > 0 {
64 resolved = names[0]
65 // remove trailing dot if present
66 if len(resolved) > 0 && resolved[len(resolved)-1] == '.' {
67 resolved = resolved[:len(resolved)-1]
68 }
69 }
70
71 elapsed := time.Since(start)
72 if debugTiming && elapsed > 50*time.Millisecond {
73 fmt.Fprintf(os.Stderr, "[timing] slow DNS lookup: %s -> %s (%v)\n", addr, resolved, elapsed)
74 }
75
76 // cache the result (unless caching is disabled)
77 if !r.noCache {
78 r.mutex.Lock()
79 r.cache[addr] = resolved
80 r.mutex.Unlock()
81 }
82
83 return resolved
84}
85
86// ResolvePort resolves a port number to a service name
87func (r *Resolver) ResolvePort(port int, proto string) string {

Callers 15

ResolveAddrPortMethod · 0.95
ResolveAddrsParallelMethod · 0.95
TestResolveAddr_CachingFunction · 0.80
TestClearCacheFunction · 0.80
TestGetCacheSizeFunction · 0.80

Calls

no outgoing calls

Tested by 12

TestResolveAddr_CachingFunction · 0.64
TestClearCacheFunction · 0.64
TestGetCacheSizeFunction · 0.64
TestConcurrentAccessFunction · 0.64