How do I get the IP address into a batch-file variable?

The following code works on any locale of any platform since Windows XP and it looks for the network IP from a (more or less) random of your network cards. It will never take longer than a few milliseconds.

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

The following one looks for your public IP instead and works on Windows 7 and newer machines.

for /f %%a in ('powershell Invoke-RestMethod api.ipify.org') do set PublicIP=%%a
echo Public IP: %PublicIP%  

You can find detailed explanations of these commands on my blog.

Leave a Comment