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

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制