Search code examples
loopsbatch-fileippingrestart

Restart server based on ping response


I've created this from a mashup of other questions/answers on this site, as well as stuff found at ss64.com

I've hammered it down to what I want, now it's just a crucial missing detail that will make it loop over and over until the connection has been established while avoiding constantly starting the server on each cycle.

It's massively over-engineered and horrendously made, but it's basically the culmination of all I've learned and just working it out in a way I can understand.

The main issue with it right now is if it's less than 100% packet loss, it will start the server, even if it's 80% packet loss which is too high for anything to connect or function on.

I'm looking for that crucial command to ensure the server will only start if there is 100% connection and also make sure it wont keep starting the server if there is 100% connection in a continued loop (which has happened far too many times, 50 instances of a server running really is a PC killer).

Here is what I have (don't laugh too hard).

@echo off 
title Server Restart
color 0A
cls
:start
Cls
set ip=xxx.xx.xxx.xx

:ping
ping %ip% -n 5 || goto PingFail
timeout /t 8
cls
echo Ping was Successful to %ip% at %date% %time%
timeout /t 10
ping %ip% -n 5 -w 5000 && goto start
echo Moving To PingFail...
goto PingFail


:Starting
Echo Connection Established... Starting server
**Start Server.bat**
Echo Start Successful
goto start


:PingFail
cls
Echo Connection Has Failed.. looping.
timeout /t 3
goto Pingloop


:Pingloop
echo PINGLOOPING
ping %ip% -n 5 || goto Pingloop
timeout /t 15
goto Starting

Solution

  • What kind of servers are we talking about? And you are aware that most firewalls block ping request by default right? You can use: https://uptimerobot.com/ and use their API to get valid information.

    If you want to be sure you that you have a connection to the outside world you can check for 0% loss like this:

    ping -n 1 -4 www.google.com | grep "0% loss"
    

    I have never seen 80% or 60% loss but of course you can change 0% to whatever percentage. Though pinging your own public IP doesn't mean you have a working internet connection. You need to ping the 'world' not your home.