A practical C# walkthrough of reading live IPv4 default gateways from System.Net.NetworkInformation and comparing hosts with byte-level subnet masking, including the virtual adapter, VPN and routed-target traps that break naive network tools.
Key points
- NetworkInterface.GetAllNetworkInterfaces() with OperationalStatus.Up still returns loopback, tunnel and virtual switches.
- Filter GatewayAddresses by AddressFamily.InterNetwork and drop IPAddress.Any so 0.0.0.0 placeholder gateways are skipped.
- Read unicast IPv4Mask defensively: it can be null or IPAddress.Any on unconfigured and point-to-point adapters.
- IsInSameSubnet() ANDs the address bytes with the mask, so a /22 works where a hardcoded /24 silently fails.
- An RFC 1918 check is a handful of byte comparisons over 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16.
- GetIPProperties() does not order gateways by route priority; GetIPv4Properties().Index plus OS metrics decide egress.
Why it matters
The API surface here is old and dependency-free, so the real value is the filtering discipline: most bugs in these utilities come from trusting the first adapter that reports Up. Anyone writing an installer, an IoT provisioning step or an internal health probe should put the adapter, gateway and mask checks in before shipping, because the behaviour differs on Windows, Linux and macOS — IPv4Mask is not always available.
Two limits to remember: everything stops at IPv4, and gateway order is not route order, so pick egress by interface index and OS metrics. Treat a subnet mismatch as "routed", not "unreachable".
Real-world use
- A desktop network diagnostics tool that must find the real default gateway on a machine running Docker, WSL or a VPN client.
- An IoT onboarding flow that checks whether a device address sits on the local subnet before connecting to it.
- A local service monitor deciding whether a target is reached on the same L2 segment or only through the gateway.
- Split-tunnel VPN workstations where several adapters expose a valid IPv4 gateway at once.
This summary was generated by the agent from the original post on C# Corner. The full text and all rights belong to its author and publisher. Go to original