Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set timeout while doing a net.DialTCP in golang?

Tags:

go

As net.DialTCP seems like the only way to get net.TCPConn, I'm not sure how to set timeouts while doing the DialTCP. https://golang.org/pkg/net/#DialTCP

func connectAddress(addr *net.TCPAddr, wg *sync.WaitGroup) error {
    start := time.Now()
    conn, err := net.DialTCP("tcp", nil, addr)
    if err != nil {
        log.Printf("Dial failed for address: %s, err: %s", addr.String(), err.Error())
        return err
    }
    elasped := time.Since(start)
    log.Printf("Connected to address: %s in %dms", addr.String(), elasped.Nanoseconds()/1000000)
    conn.Close()
    wg.Done()
    return nil
}
like image 635
Abhijeet Rastogi Avatar asked Nov 05 '17 03:11

Abhijeet Rastogi


2 Answers

Use net.Dialer with either the Timeout or Deadline fields set.

d := net.Dialer{Timeout: timeout}
conn, err := d.Dial("tcp", addr)
if err != nil {
   // handle error
}

A variation is to call Dialer.DialContext with a deadline or timeout applied to the context.

Type assert to *net.TCPConn if you specifically need that type instead of a net.Conn:

tcpConn, ok := conn.(*net.TCPConn)
like image 104
Bayta Darell Avatar answered Nov 22 '22 08:11

Bayta Darell


One can use net.DialTimeout:

func DialTimeout(network, address string, timeout time.Duration) (Conn, error)
    DialTimeout acts like Dial but takes a timeout.

    The timeout includes name resolution, if required. When using TCP, and the
    host in the address parameter resolves to multiple IP addresses, the timeout
    is spread over each consecutive dial, such that each is given an appropriate
    fraction of the time to connect.

    See func Dial for a description of the network and address parameters.
like image 28
jeanluc Avatar answered Nov 22 '22 09:11

jeanluc