shadyabhi
shadyabhi

Reputation: 17234

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

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
}

Upvotes: 16

Views: 32963

Answers (2)

jeanluc
jeanluc

Reputation: 1708

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.

Upvotes: 11

Thundercat
Thundercat

Reputation: 120941

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)

Upvotes: 31

Related Questions