Articles

Tuesday, January 10, 2012

CMD Shell tricks

Recently there was a post on the alt.msdos.batch.nt news group where someone needed to get an IP address into a variable. Sounds easy enough, but the problem he was having was that he couldn't use typical parsing with the findstr command because the language settings were not consistent between systems.

The easiest way to get your local IP address into a variable is like this:

# for /f "tokens=2 delims=[]:" %i in ('ping -n 1 -4 %computername% ^| findstr /i "pinging"') do set ip=%i& echo %ip%


This works fine most of the time, but what if you have multiple interfaces on your system? Consider this:



# for /f "tokens=2 delims=[]:" %i in ('ping -4 -n 1 %computername% ^| findstr /i
"pinging"') do set ip=%i& echo %ip%
169.254.238.27


#


What is that address? That's an APIPA address that Microsoft so graciously provided us in case we were unable to receive an IP address from a DHCP server. This isn't our actual IP address that we are using on the LAN, so this isn't the output we want.

Going back to our original problem, the findstr /i "pinging" won't work because the language was different. So, we need another way to determine this, while also maintaining backwards compatibility with older systems such as Windows 9x systems. Here is my solution to the problem:



# for /f "tokens=3 delims=:" %i in ('arp -a ^| findstr /n /l ":" ^| find "2:"')
do @for /f %z in ('echo %i') do @set ip=%z


#echo %ip%
172.16.2.13


#