How to get and use your local IP address in a Windows 7 (and Vista) batch command file

Published: | by Julian Knight Reading time ~2 min.
📖 Posts | 📎 Windows | 🔖 batch, vista, win7

If, like me, you spend a lot of time on a variety of customer sites, you will probably be familiar with the issues around swapping networks. I’ve already blogged about the problems with Windows 7, Vista and Firefox proxy settings and I will do some more articles on getting on with problematic proxies later. However, I wanted to let people know how to get hold of your IP address from within a batch (command) file.

@REM ipconfig | find “IPv4 Address”
@REM Find the IPv4 address from ipconfig (13th var if string is split by both @REM and space)
@for /f “usebackq tokens=13 delims=: “ %%i in (ipconfig ^| find "IPv4 Address") do @(
   @set MyIP=%%i
   @REM Split addr into components so networks can easily be checked
   @for /f “usebackq tokens=1-4 delims=.” %%a in (‘%%i’) do @(
      @REM @echo %%a,%%b,%%c,%%d
      @set MyIP1=%%a
      @set MyIP2=%%b
      @set MyIP3=%%c
      @set MyIP4=%%d
Note the space after the : on line 3. The FOR command used twice here splits the text output from what is in the () after the “in” using the defined delimiters (“:” and space in the 1st case, “.” in the 2nd). In the first FOR statement, we take element number 13 only, it ends up in variable %%i. In the second case, we take elements number 1 to 4, they go into variables %%a, %%b, %%c, %%d. Now you have not only the full address but also the componants so if you wanted to check whether you were in a particular class C network, you could do something like:
@set corp_addr_ip4=
@if “%MyIP1%.%MyIP2%.%MyIP3%.0”==“%corp_addr_ip4%” @goto DOSOMETHING
That would check if your local IP address is between and Note that I’ve used the enhanced FOR statement – the “usebakq” makes the FOR statement more like a UNIX type one where commands are enclosed in back-quotes (`). This certainly works for Windows 7 and should, I think, work for Vista. Prior to Vista, you would need to do things differently anyway. At the very least you would have to search for “IP Address” in the FIND statement as IPCONFIG didn’t include IPv6 information. Now that you have everything in place, you can control the proxy settings for each application that needs access out of the local network. I’ll blog about that another time.

Technorati : , , ,
Diigo Tag Search : , , ,

comments powered by Disqus