Obtain IP Address (and parse Octets) and Gateway from DOS

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
viroid
Posts: 8
Joined: 04 Jan 2010 15:49

Obtain IP Address (and parse Octets) and Gateway from DOS

#1 Post by viroid » 12 Jan 2010 20:15

This is really useful for running domain login scripts based on IP Subnet.

Six months ago when I was trying to figure out how to do this, I couldnt. Most results on google returned the use of a third party application that needed to be installed on every workstation in the domain in order to process the loginscript correctly. I ended up utilizing the %logonserver% variable to select the logonscript because the hostnames of our domain controllers are prefixed with their location. But this wouldn't work for everyone. With what I've learned in the past week since finding this site, I was able to write the following code which solved ALL my problems, I implimented it last night in my domains logonscript and it's working perfectly.



REM.-- Beginning of application --

route print 0.0.0.0 |findstr 0.0.0.0 > tmp.txt
for /f "tokens=3,4" %%a in (tmp.txt) do (
set gateway=%%a
set ipaddress=%%b
)
del tmp.txt

for /f "tokens=1-4 delims=." %%i in ("%IPADDRESS%") do (
set ipoct1=%%i
set ipoct2=%%j
set ipoct3=%%k
set ipoct4=%%l
)


IF "%ipoct3%"=="10" cscript "%LOGONSERVER%\NETLOGON\MapPrinters_VA.vbs"
IF "%ipoct3%"=="11" cscript "%LOGONSERVER%\NETLOGON\MapPrinters_IL.vbs"
IF "%ipoct3%"=="12" cscript "%LOGONSERVER%\NETLOGON\MapPrinters_MO.vbs"


:EOF



... Enjoy! Hope someone finds this useful.

HumanJHawkins
Posts: 1
Joined: 13 Jun 2013 15:33

Re: Obtain IP Address (and parse Octets) and Gateway from DO

#2 Post by HumanJHawkins » 13 Jun 2013 15:45

It seems that the IP Address part of the "route print" output doesn't follow a format that is easily parsed when there are multiple connections. I.e. wired and wireless on a laptop.

So this part of the code:

Code: Select all

route print 0.0.0.0 |findstr 0.0.0.0 > tmp.txt 
for /f "tokens=3,4" %%a in (tmp.txt) do (
set gateway=%%a
set ipaddress=%%b
)
del tmp.txt


Can be replaced with this (which also doesn't need a temp file):

Code: Select all

FOR /f "TOKENS=3" %%a IN ('ROUTE PRINT 0.0.0.0 ^|FIND " 0.0.0.0 "') DO (SET Gateway=%%a) 
FOR /F "TOKENS=1-2 DELIMS=:" %%a IN ('IPCONFIG^|FIND "IPv4"') DO (SET IPADDRESS=%%b)
::Trim the result (It will contain a leading space)
SET IPADDRESS=%IPADDRESS:~1%


Thanks much for the Octet parsing bit.

Post Reply