Finding the first (default) IPv4 gateway in a Windows batch script

I recently had to whip out my batch scripting skills to grab the default gateway for a routing script. Here’s what I ended up with:

route print | findstr /R /C:"^[ ][ ]*0.0.0.0[ ]" | for /f "tokens=3" %%i in ('more') do (echo %%i & exit) >gw.tmp
set /P gw=<gw.tmp
del gw.tmp
echo "%gw%"

This does, unfortunately, use a temporary file (gw.tmp), and I didn’t find a non-clunky way around that. But it works, for now 🙂

Suggestions on more elegant ways of doing this in a pure batch script are welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *