For scripting purposes, I've found that curl
command can do it, for example:
$ curl -s localhost:80 >/dev/null && echo Connected. || echo Fail.
Connected.
$ curl -s localhost:123 >/dev/null && echo Connected. || echo Fail.
Fail.
Possibly it may not won't work for all services, as curl
can return different error codes in some cases (as per comment), so adding the following condition could work in reliable way:
[ "$(curl -sm5 localhost:8080 >/dev/null; echo $?)" != 7 ] && echo OK || echo FAIL
Note: Added -m5
to set maximum connect timeout of 5 seconds.
If you would like to check also whether host is valid, you need to check for 6
exit code as well:
$ curl -m5 foo:123; [ $? != 6 -a $? != 7 ] && echo OK || echo FAIL
curl: (6) Could not resolve host: foo
FAIL
To troubleshoot the returned error code, simply run: curl host:port
, e.g.:
$ curl localhost:80
curl: (7) Failed to connect to localhost port 80: Connection refused
See: man curl
for full list of exit codes.