1

I currently have this simple line in order to write the IP in the console

for /f "tokens=14 skip=34 delims= " %%a in ('ipconfig') do (echo %%a)

Yet, when I try to input this info into a file, it'll just display the last character shown in the command, which is ":", but I need to extract solely the first line into a text file %temp%\Test.txt so I later save it into a variable through

set /p IP=< %temp%\Test.txt

Tried with Type, but didn't work, I'm currently codeblocked, any ideas?

NibboNSX
  • 49
  • 1
  • 5
  • Possible duplicate of [How do I get the IP address into a batch-file variable?](https://stackoverflow.com/questions/5898763/how-do-i-get-the-ip-address-into-a-batch-file-variable) –  Oct 25 '18 at 17:56

1 Answers1

1

The solution is not mine, but a blogger called Fabio Iotti. Kudos to him.

for /f "delims=[] tokens=2" %%a in ('ping -4 -n 1 %ComputerName% ^| findstr [') do set NetworkIP=%%a
echo Your IPv4 is: %NetworkIP%

What I liked for that solution, besides being it a clever way to get it, is that it will output a clean IP variable, so you will not have to worry about snip the string.

Let's take a look at it.

When ping is run, it will show the IP between brackets. Pinging your own computer with %ComputerName% will force the command to show your own IP.

Finally, the wide options that findstr allows with the use of wildcards allow us to gather the information between the brackets (Remember the [') ?), resulting in a clean variable that will only show your IP.

However, I am not sure how this will work if you are connected via WiFi / LAN / USB / Cellular or any other internet capability; how does Windows handle the IPv4 with several connections methods? I am sure that it will be not a problem, but I would like to check it out.