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.