Home > Software engineering >  getting ip from ping command and storing in batch file variable
getting ip from ping command and storing in batch file variable

Time:08-17

Was looking for a way to get the IP address of another computer on the network. Found this excellent code in another thread:

for /f "tokens=2 delims=[]" %f in ('ping -4 -n 1 piratelufi.com ^|find /i "pinging"') do echo %f

However, I have 2 issues:

  1. Need to be able to run this inside a CMD file. When I tried, it didn't seem to work. Everything I read said that it should work, but when I ran the CMD file, nothing happened.
  2. I need to be able to store the resulting IP address value in a variable so that I can use it in another command within the same CMD file. It appears the variable %f already has the value, but when I run this command in a CMD file, and try to access the %f, nothing happens.

Wondering if anyone knows a way to modify this so I run this code in a CMD file and grab that IP for use in another command?

Thanks!

CodePudding user response:

Try this. Has two set PCName lines that you can REM out one and un-REM the other to see that it gives a different IP.

@ECHO OFF
SET "PCName=piratelufi.com"
REM SET "PCName=google.com"
FOR /F "tokens=2 delims=[]" %%F IN ('PING -4 -n 1 %PCName%') DO SET "PCIP=%%F"
ECHO {%PCIP%}

EDIT: Thank you to Stephan for pointing out that FIND was doing nothing of value, and was actually creating an unnecessary dependency. PING produces only one line that tokens=2 delims=[] matches, resulting in only one execution of DO. Above script now has FIND removed. {My bad for not inspecting the original code for what it was, and was not, doing.}

CodePudding user response:

In this batch script : We can extract the IP from ping results and we can add a loop if you want to check its state every minute !


@echo off
set "Link=piratelufi.com"
Title Ping Tester for "%Link%"
:MainPing
set "state="
setlocal enableextensions enabledelayedexpansion
@for /f "tokens=2 delims=[]" %%b in ('ping -4 -n 1 !Link!') do set "ip=%%b"
    ping -n 1 !Link!>nul && set "state=UP" || set "state=Down"
)
:Myloop
echo.            
  • Related