curl / Mailing Lists / curl-users / Single Mail
Buy commercial curl support from WolfSSL. We help you work out your issues, debug your libcurl applications, use the API, port to new platforms, add new features and more. With a team lead by the curl founder himself.

Using curl to test if a port is open: exit immediately upon connection if STDIN is /dev/null

From: Robin A. Meade via curl-users <curl-users_at_lists.haxx.se>
Date: Thu, 21 Apr 2022 16:52:37 -1000

Suggestion:

Make curl exit immediately with code 0 upon successful telnet connection
if STDIN is initially EOF.

That is, the following command would exit immediately after the
connection is established with exit code 0:

curl -s --connect-timeout 2 telnet://example.com:80 </dev/null


Discussion:

curl's telnet protocol support is often used interactively to test if a
port on a remote server is open [1][2][3]

[1]: https://www.cyberithub.com/check-test-port-connectivity-in-linux/
[2]: https://www.unixtutorial.org/test-tcp-connectivity-with-curl/
[3]:
https://www.computertechblog.com/testing-a-tcp-port-with-curl-in-linux/

When used in a script, though, there is the need to make curl exit
immediately upon successful connection. [1][2]

[1]: https://stackoverflow.com/q/42347271
[2]: https://stackoverflow.com/q/64106136

My best attempt at achieving this is to purposely pass an unknown telnet
option and test if the exit code is 48 (CURLE_UNKNOWN_OPTION):

curl -t 'DUMMY=1' -s --connect-timeout 2 telnet://example.com:80 </dev/null

Alternatively, pass an empty string as the telnet option and test for
exit code 49 (CURLE_SETOPT_OPTION_SYNTAX). I formalized this latter
approach as a function:


# Args:
# 1 - host
# 2 - port
tcp_port_is_open() {
   local exit_status_code
   curl -t '' --connect-timeout 2 -s telnet://"$1:$2" </dev/null
   exit_status_code=$?
   case $exit_status_code in
     49) return 0 ;;
     *) return "$exit_status_code" ;;
   esac
}


Tests:

tcp_port_is_open example.com 80
echo "$?"
# 0 ✔️

tcp_port_is_open example.com 1234
echo "$?"
# 28 - Operation timeout ✔️

tcp_port_is_open non.existent.example 80
echo "$?"
# 6 - Couldn't resolve host. ✔️


-- 
Unsubscribe: https://lists.haxx.se/listinfo/curl-users
Etiquette:   https://curl.haxx.se/mail/etiquette.html
Received on 2022-04-22