Question

I'd like to be able to run a single batch file that would find the IP address of every device connected to my router, and then find their hostnames from it. What I have so far is below:

@echo off

set /a n=0
:repeat
set /a n+=1
echo 192.168.1.%n%
ping -n 1 -w 500 192.168.1.%n% | FIND /i "Reply">>devices.txt
if %n% lss 254 goto repeat
type devices.txt
goto :hostname

This finds all the possible addresses and writes them to a text file, devices.txt. However, I now end up with the following:

Reply from 192.168.1.82: bytes=32 time=5ms TTL=255

The next part of the batch file goes:

:hostname 
ping -a %ip% -l 1 -n 1 >> hostnames.txt

This pings the IPs found in devices.txt and returns the result in hostnames.txt - or at least, I'd like it to.

Somehow I need to separate the IP address from the other text when writing it to devices.txt, and then assign it as a variable so it can be used by the next part.

Is there a simple function I can use to do either of these things?

Was it helpful?

Solution

Try this:

@echo off
setlocal 

set "p=ping -n 1 -w 500 192.168.1"
for /l %%a in (1,1,254) do (
    for /f "Tokens=3 delims=: " %%b in (
      '%p%.%%a^|Find /i "TTL="'
    ) do (
      echo Pinging %%b
      echo %%b>>devices.txt
      for /f "tokens=2" %%c in (
        'ping -a %%b -l 1 -n 1^|Find /i "pinging"') do (
           echo %%c >>hostnames.txt
      )
    )
)

We start by creating a For /L loop that goes from 1 to 254 in increments of 1. Then we run a for loop on a ping command that takes the third token on the return line and puts it into a variable, %%b in this case. We then echo out pinging IP address contained in %%b and write it to devices.txt. Then, we run another ping to extract the second token which is the hostname of the computer we're pinging and write it out to hostnames.txt.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top