Windows command-line: Fastest way to disable internet (keeping LAN)?

Split question: this other one here is for Linux.

I think the easiest way to deactivate internet (not LAN) in Windows command-line is to remove the default gateway, so, assuming LAN is 10.0.2.0/24 and gateway is 10.0.2.1 :

`route delete 0.0.0.0 mask 0.0.0.0 10.0.2.1`  

To reactivate internet:

`route add 0.0.0.0 mask 0.0.0.0 10.0.2.1`

But, even when this a simple line, it requires to discover the default gateway IP first:

  • In Windows:

    route print

I am going to build some general purpose shell scripts that need to enable/disable internet(but keep LAN working), so it seems I am going to need some grep equivalent operations to filter and detect the exact gateway IP number (it could be 10.0.2.1, 127.0.0.1, 127.0.50.1, 192.168.0.1 ... etc), unless I achieve to find a simpler command line.
Any ideas, please?

  • EDIT: Some people reports that gateway deletion in Windows could also be done like this:

route delete 0.0.0.0

So, apparently, there would be no problem in modifying the deletion script made by @and31415 .


Solution 1:

Batch scripts

Similar to @John1024's approach, here's how you can do it in Windows:

Disable

@echo off
cd /d "%~dp0"

REM retrieve the current gateway
set dest=0.0.0.0
for /f "tokens=2,3" %%A in ('"route print %dest% | findstr /c:"%dest%" "') do (

REM save the IP and delete the gateway
echo %%A %%B>%dest%.txt
route delete %dest% >nul
)
exit /b

Enable

@echo off
cd /d "%~dp0"

REM ensure the settings file exists
set dest=0.0.0.0
if not exist %dest%.txt exit /b 2

REM restore the default gateway
for /f "tokens=1,2" %%A in (%dest%.txt) do (route add %dest% mask %%A %%B >nul)
exit /b