'close curl connection after telnet
What I Want:
After a successful connection, I want curl to exit successfully. I am running this command inside a container, so I want the curl command to exit successfully so that the container will too.
Here is my example:
$ curl -v telnet://google.com:443/
* Trying 172.217.197.113...
* TCP_NODELAY set
* Connected to google.com (172.217.197.113) port 443 (#0)
Options I have tried:
No Keep Alive:
$ curl -v --no-keepalive telnet://google.com:443/
* Trying 172.217.197.102...
* TCP_NODELAY set
* Connected to google.com (172.217.197.102) port 443 (#0)
Connection Timeout:
$ curl -v --connect-timeout 5 telnet://google.com:443/
* Trying 172.217.197.139...
* TCP_NODELAY set
* Connected to google.com (172.217.197.139) port 443 (#0)
Keep Alive Time:
$ curl -v --keepalive-time 5 telnet://google.com:443/
* Trying 172.217.197.139...
* TCP_NODELAY set
* Connected to google.com (172.217.197.139) port 443 (#0)
Flag Definitions
--no-keepalive (Disable keepalive use on the connection)
--connect-timeout (SECONDS Maximum time allowed for connection)
--keepalive-time (SECONDS Wait SECONDS between keepalive probes)
Solution 1:[1]
What worked for me was sending "exit" to telnet and since you are not intressted in the output, redirect it
$ echo "exit" | curl --connect-timeout 1 -s telnet://google.com:443 > /dev/null
$ echo $?
0
$ echo "exit" | curl --connect-timeout 1 -s telnet://google.com:4433 > /dev/null
$ echo $?
7
Solution 2:[2]
To make curl exit immediately upon successful telnet connection, purposely pass an unknown telnet option and test if the exit code is 48:
curl -t 'DUMMY=1' --connect-timeout 2 -s telnet://google.com:443 </dev/null
[ "$?" -eq 48 ]
echo "$?"
# 0
48 is curl's error code for "An option passed to libcurl is not recognized/known."
— https://curl.se/libcurl/c/libcurl-errors.html
This works because the telnet options are processed only after a successful connection.
Edit: May 27, 2022: Watch this todo item:
https://curl.se/docs/todo.html#exit_immediately_upon_connection
Via: https://curl.se/mail/archive-2022-04/0027.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Philipp Aeschlimann |
Solution 2 |