I use this function to limit response time from DNS server
func LookupHost(hostname string, timeout time.Duration) ([]string, error) {
c1 := make(chan []string)
c2 := make(chan error)
go func() {
var ipaddr []string
ipaddr, err := net.LookupHost(hostname)
if err != nil {
c2 <- err
close(c2)
}
c1 <- ipaddr
close(c1)
}()
select {
case ipaddr := <-c1:
return ipaddr, nil
case err := <-c2:
return []string{}, err
case <-time.After(timeout):
return []string{}, errors.New("timeout")
}
}
The problem is that this function eat memory.
I think it is because I break net.LookupHost(hostname)
syscall.
Any way to avoid this?
May be some other way how to query DNS servers with timeouts?
You can check an alternative implementation proposed in bogdanovich/dns_resolver
Its dns_resolver.go
does include timeout management
resolver := dns_resolver.New([]string{"8.8.8.8", "8.8.4.4"})
// OR
// resolver := dns_resolver.NewFromResolvConf("resolv.conf")
// In case of i/o timeout
resolver.RetryTimes = 5
You can then wrap the all call in a goroutine, in order for the call to not break abruptly net.LookupHost()
.
ip, err := resolver.LookupHost("google.com")
if err != nil {
log.Fatal(err.Error())
}
log.Println(ip)
// Output [216.58.192.46]