user3385003
user3385003

Reputation: 1

If expression based on a Pings TTL value?

I've been creating a few batch tools to assist in Pinging handfuls of machines. I've been calling the %errorlevel% in my if expressions to check for a valid connection. But recently I've noticed an issue with this. Sometimes a machine will Reply but will actually fail to send Packets back. This would be considered an invalid connection, but the %errorlevel% still produces a 0.

My question is, instead of using %errorlevel% is there a way to call the TTL value or Time value from the ping? I think I'm missing an API here....

Upvotes: 0

Views: 2489

Answers (1)

MC ND
MC ND

Reputation: 70923

In windows, ping command sets errorlevel if any of the sent packets is lost. If some packets are received and other are lost, errorlevel is set. But, in ipv4, pinging a non active machine in the same subnet, you can get a "Unreachable" message and no packet lost. So, in ipv4, the best option is to check for the presence of the "TTL=" text in the output of ping command. And better include the equal sign to avoid the TTL expired messages.

In ipv6, the output of the ping command does not contain the "TTL=" information. It will also set the errorlevel in the case of packets lost, but, for addresses in the same subnet, if the machine is not alive, all the packets are lost.

So, the "best" strategy for ping checking is: If address is ipv6, check the errorlevel. If address is ipv4 check for presence of "TTL=". find command is a usual tool to do it, as it sets the errorlevel variable if the indicated text if not found. Something like

ping -4 xxx.xxx.xxx.xxx | find "TTL=" >nul 
if errorlevel 1 (
    echo not alive
) else (
    echo alive
)

Upvotes: 1

Related Questions