Batch File get Specific IP into Variable

2.2k views Asked by At

I am trying to select a specific IP address in a windows batchfile. This line of code works, but gets the wrong IP address:

for /f "delims=: tokens=2" %%a in ('ipconfig ^| findstr /R /C:"IPv4 Address"') do (set newip=%%a)

If I type this at the command line, it gets a single line containing the IP address I'm looking for:

netsh interface IPv4 show addresses "Ethernet 2" | findstr /R /C:"IP Address"

However, when I try to embed that into the line from above to get the IP address into a variable, it throws the error "'else' is not recognized as an internal or external command, operable program or batch file.'

for /f "delims=: tokens=2" %%a in ('netsh interface IPv4 show addresses "Ethernet 2" ^| findstr /R /C:"IP Address"') do (set newip=%%a)

Any thoughts what I'm doing wrong?

FYI, the reason why I'm trying to select this is that I have a program that sets an entry in my hosts file to point to my current IP, so that the site I'm running locally can use a specific domain. The problem with the existing code is that I have two IPv4 addresses - one from a VPN, and the other from my local router - and that code is selecting the wrong IP address.

Many thanks!

1

There are 1 answers

1
AudioBubble On BEST ANSWER

Your findstr parameters are wrong. You have specified use regular expression AND use literal. RegEx will win so you are searching for IP OR Address. Remove the /r.

Also your tokens/delims are wrong - you are getting a lot of spaces in your variable. This makes colon and space a delimiter.

for /f "tokens=3 delims=: " %a in ('netsh interface IPv4 show addresses "local area connection 7" ^| findstr /C:"IP Address"') do (set newip=%a)

How did I discover this. I unwound your command back to individual commands and ran each of those. Once I could see the output it was obvious.