16

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
}

2 Answers 2

31

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Is Timeout field counted as a counterpart for curl's --connect-timeout? Or is that like --max-time?
As a side note, net.Dial() will try to resolve the address while net.DialTCP() does not. This can be a performance concern or not, depending on you use case
The problem is that net.DialTCP is not completly the same as net.Dialer{}.Dial the first one has localAddr parameter but general dialer not.
@Oleg Use the dialer's LocalAddr field to specify the local address.
11

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.