Search code examples
linuxbashnetwork-programmingporttelnet

How can I loop until IP:port is not responding


Our mail server stopped to listen on 587 from our workplace.

We restarted it twice and we are now watching the logs.

It seems that we loose the tcp connection, I want to see when it happen so I can finally get to the error.

For this reason, I am looking to test in loop that the tcp connection is open, until it crash. How can I achieve this?

Is this reliable:

while nc -z hostname port; do sleep 5; done

It sounds like it will only test once when I run nc -z mail.gmail.com 587 and nc -z mail.gmail.com 588 I don't get the error code I am expecting for each case.


Solution

  • I am not sure I understand what you're asking exactly, but lets hope this is what you mean!

    As google.com my not fail, I would recommend disconnect your internet to test. Use your IP instead of google.com and your port instead of 80.

    #!/bin/bash
    for i in `seq 1 10`;
    do
            nc -z -w 1 google.com 80 &> /dev/null
            if [ $? -eq 0 ]; then
                echo OK
            else
                echo FAIL
            fi
    done