duanke6057 2016-10-29 03:50
浏览 100
已采纳

按时间中断net.LookupHost时golang内存泄漏

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?

  • 写回答

1条回答 默认 最新

  • drmq16019 2016-10-29 06:08
    关注

    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]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度