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
}
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With