How to Set Curl TCP Connection Timeout
This article explains how to configure a specific connection timeout
for the TCP handshake phase in curl using the
--connect-timeout option. By limiting this initial phase,
you can prevent your command-line requests and scripts from hanging
indefinitely when attempting to connect to offline or unresponsive
servers.
To limit the time curl spends attempting to establish a
connection—which primarily consists of the TCP handshake—you should use
the --connect-timeout option. This restricts only the
connection phase and does not affect the time it takes to transfer data
once the connection is established.
Using the
--connect-timeout Option
To restrict the connection phase, append
--connect-timeout followed by the maximum number of seconds
you want to allow:
curl --connect-timeout 5 https://example.comIn this example, if the TCP handshake takes longer than 5 seconds,
curl will abort the attempt and return an exit code
(typically exit code 28, indicating a timeout).
Using Decimal Values for Sub-Second Precision
Modern versions of curl support decimal values, allowing
you to define precise, sub-second timeouts for low-latency
environments:
curl --connect-timeout 0.5 https://example.comThis configuration limits the TCP connection phase to exactly 500 milliseconds.
Difference
Between --connect-timeout and --max-time
It is crucial to distinguish between the two timeout options
available in curl:
--connect-timeout <seconds>: Limits only the initial connection phase (the TCP handshake and SSL/TLS negotiation). Once the connection is successfully established, this timer stops.-mor--max-time <seconds>: Limits the total duration of the entire operation, from the initial connection attempt to the final byte of the data transfer.
To ensure a fast failure if the server is offline, but still allow ample time for a large file download once connected, you can combine both options:
curl --connect-timeout 3 --max-time 60 https://example.com/largefile.zip