• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

Check connection with timeout, script telnet web server in script


Active Member

Thanks: 14
Messages: 101

Hi guys, Im having trouble finding the way to:

Check the connection if it has been established with timeout:

1. Create the connection
2. Check if it has been established
3. If yes, then do something
4. If no, for timeout = 5 seconds, exit with error code.

Netcat sounds like a perfect tools for this task:

nc -w 5 domain.com port
But the timeout switch takes no effect. I googled and many others reported the same symptom

Script to telnet web server

Please see the attachment, I cant post here, for some reasons the forum complained the code with the "bad request" error

A similar script I wrote before was working, but unfortunately I forgot to keep copy of it. This time, it doesnt work. I must have syntax errors somewhere.



Staff member

Thanks: 2,560
Best answers: 1
Messages: 11,164

You could try net/tcping from ports.

# tcping -t 5 www.google.com 80
www.google.com port 80 open.
# echo $?
# tcping -t 5 www.google.com 90
www.google.com port 90 user timeout.
# echo $?
Easy to use in scripts:

if ( tcping -q -t 5 www.google.com 80 ); then echo alive; else echo dead; fi

if ( tcping -q -t 5 www.google.com 90 ); then echo alive; else echo dead; fi
Don't use 80 as a check port when you're behind a proxy server ;)


Active Member

Thanks: 14
Messages: 101

Thanks, but the script will be run in web server, so I cant install any 3rd party application.


Active Member

Thanks: 14
Messages: 101

Hi DutchDaemon,

My web server running Linux, there is no -o switch for netcat

Let me elaborate a bit more in details. In my case, it takes about 2 seconds to establish a new connection (a deamon with listening port)

I run this command in background mode:

$ command to create new connection &
Then I run netcat. Instead of keeping trying to connect for 5 seconds, netcat quits immediately if it fails at the first attempt:

nc -zw 5 hostname port
Thats why I said the timeout feature takes no effect.


Active Member

Thanks: 14
Messages: 101

I came up with this function:

repeatCMD () {

    while [ $? -ne 0 ]; do
        sleep 1
        echo " ===> I try again..."
        count="$(($count + 1))"
        if [ $count -eq 5 ]; then
            echo " ===> ERR: Max number of retry. Quitting..."
            exit 127
Now I can run the command:

repeatCMD nc -zw 5 hostname port
It works (doesnt exactly do the same job as timeout, though)

But Im sure you guys have a more elegant solution. Seriously, 12 line of code for the timeout switch doesnt sound right.

And I havent recalled what I have done with the telnet script :S