How to set Connection and Max Timeout for cURL Request with Examples


If you want to limit the time for a cURL Request (HTTP/HTTPS/FTP/SFTP and other protocols) to try to connect to a provided host you can make use of the --connect-timeout option followed by the time specified in seconds.

--connect-timeout <fractional seconds>

--connect-timeout provided will be the maximum time in seconds that the curl connection can take to get back. If the connection is established the cURL request will continue, if not then it will exit.

Note: Since cURL version 7.32.0 connection timeout option accepts time in decimal values as well.

Let's see few examples with --connect-timeout options,


Example 1: cURL HTTP GET with Connection Timeout of 30 seconds

% curl --connect-timeout 30 http://10.20.30.1
curl: (28) Connection timeout after 30001 ms 
cURL HTTP GET with Connection Timeout of 30 seconds

As you can see the above HTTP GET cURL request failed to connect to the host IP address within 30 seconds so cURL exited with a timeout exit code (28)


Example 2: cURL HTTPS POST with Connection Timeout of 60 seconds

% curl --connect-timeout 60 --request POST '10.20.1.1' \ 
--header 'Content-Type: text/html' \
--header 'Accept-Encoding: deflate, gzip;q=1.0, *;q=0.5'
curl: (28) Connection timeout after 60006 ms
cURL HTTPS POST with Connection Timeout of 60 seconds

Example 3: cURL HTTPS GET with Connection Timeout set in fractions (decimals)

% curl --connect-timeout 5.5 https://10.20.30.1         
curl: (28) Connection timeout after 5505 ms
cURL HTTPS GET with Connection Timeout set in fractions

--max-time option

The --max-time option is what you can use with cURL in order to exit cURL even if the connection was established but the request was not completed.

You can also make use of the short-hand option parameter -m

Example 4: max timeout with 0.3 seconds

% curl --max-time 0.3 https://code2care.org
curl: (28) Operation timed out after 300 milliseconds with 14501 out of 80674 bytes received

As you may see in the above example, the max timeout is set to 300 milliseconds, in this duration, the connection to the host was established and 14501 bytes of the response data was received, but as the max time was elapsed, the curl exited even though the data transfer was in progress.

cURL max timeout with 0.3 seconds

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap