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

I recently had to whip out my Windows 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.

2 Comments

  • Cendern says:

    Instead of echoing to a file you can set the variable in the ‘do’ clause:

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

    You can also shorten the first line by putting the command directly inside the for expression, though it means you have to escape certain characters in your command (^ before |).

    for /f "tokens=3" %%a in ('route print ^|findstr /C:" 0.0.0.0"') do set gw=%%a
    echo.%%gw%% is %gw%

Leave a Reply

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