How to permanently remove default routing rule for secondary network interface from window's IP routing table in C#

38,461

Solution 1

In a command prompt

route delete 0.0.0.0 mask 0.0.0.0 172.31.96.1 -p

I'm not sure the -p flag (persistent) works with delete, though. You'll have to test it.

Solution 2

If you want it to persist thru a reboot, consider not specifying a default gateway on the secondary interface (under ipv4 for that interface in control panel) as it's not required.

Alternatively you can adjust the metric to make it a less desirable path and your primary interface will always be favored.

Solution 3

The -p argument only applies to the ADD command. Your best bet would be to permanently add a rule that increases the METRIC of the undesired network interface.

route add -p 0.0.0.0 mask 0.0.0.0 172.31.96.1 METRIC 16
Share:
38,461
user1071840
Author by

user1071840

Updated on July 09, 2022

Comments

  • user1071840
    user1071840 almost 2 years

    I've a multi-homed windows machine (Windows Server 2016) and I want to make sure that outbound traffic never goes out through secondary network interface (progammatically via C#).

    I've 2 default entries for the network interfaces in my routing table:

    Active Routes:
    Network Destination        Netmask          Gateway       Interface  Metric
              0.0.0.0          0.0.0.0      172.31.32.1    172.31.44.180     15
              0.0.0.0          0.0.0.0      172.31.96.1    172.31.96.230     15
    

    I think permanently deleting the entry for secondary network interface will be sufficient for my use case. I want only this entry to exist afterwards:

    Active Routes:
    Network Destination        Netmask          Gateway       Interface  Metric
              0.0.0.0          0.0.0.0      172.31.32.1    172.31.44.180     15
    

    I found the C# API DeleteIpForwardEntry to delete the route, but I do not know how to make this deletion permanent, so that rebooting the machine doesn't undo my change.

    Any help will be appreciated.

  • user1071840
    user1071840 over 6 years
    Thanks, but I need to do this programmatically in C#
  • Randy Slavey
    Randy Slavey over 6 years
    You can use any command prompt process in C#. stackoverflow.com/questions/1469764/run-command-prompt-comma‌​nds
  • user1071840
    user1071840 over 6 years
    -p didn't work, the deleted rule was there after reboot
  • Randy Slavey
    Randy Slavey over 6 years
    Bummer, sorry. I think static routes are stored in the registry. You could check there. (HKEY_LOCAL_MACHINE->SYSTEM->CurrentControlSet-> ->Services->Tcpip->Parameters->PersistentRoutes). See msdn.microsoft.com/en-us/library/… for related c# classes.