Files
2026-10-11 23:23:20 +00:00

58 lines
3.1 KiB
C#

using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace UCVL.VPNPlus;
internal static class PhysicalUplink
{
internal sealed record Reading(bool Success, TunRouting.PhysicalNetwork? Network);
internal static string? Fingerprint(TunRouting.PhysicalNetwork? network) => network is null ? null :
$"{network.InterfaceIndex}|{network.InterfaceName}|{network.Ipv4Address}/{network.Ipv4PrefixLength}|{network.Ipv4Gateway}|{string.Join(',', network.Ipv4DnsServers)}";
// Inspect the real /0 routes, not our node /32 bypass or TUN /1 routes.
// MIB_IPFORWARDROW.Metric1 includes the Windows interface metric.
internal static Reading Read(int? preferredIndex = null)
{
try
{
var networks = new List<TunRouting.PhysicalNetwork>();
foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus != OperationalStatus.Up || nic.NetworkInterfaceType == NetworkInterfaceType.Loopback ||
nic.Name.StartsWith(TunRouting.AdapterName, StringComparison.OrdinalIgnoreCase)) continue;
var properties = nic.GetIPProperties();
var index = properties.GetIPv4Properties()?.Index;
if (index is null) continue;
var addresses = properties.UnicastAddresses.Where(a => a.Address.AddressFamily == AddressFamily.InterNetwork &&
a.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred && !IPAddress.IsLoopback(a.Address) &&
!a.Address.ToString().StartsWith("169.254.", StringComparison.Ordinal)).ToArray();
var dns = properties.DnsAddresses.Where(a => a.AddressFamily == AddressFamily.InterNetwork &&
!IPAddress.IsLoopback(a) && !a.Equals(IPAddress.Any)).Distinct().ToArray();
foreach (var a in addresses)
networks.Add(new(nic.Name, index.Value, a.Address, a.PrefixLength, IPAddress.Any, dns));
}
return new(true, Select(networks, new WindowsRouteTable().Snapshot(), preferredIndex));
}
catch (Exception e) when (e is NetworkInformationException or SocketException or IOException or System.ComponentModel.Win32Exception)
{
// A failed snapshot is not evidence of an offline network.
return new(false, null);
}
}
internal static TunRouting.PhysicalNetwork? Select(IEnumerable<TunRouting.PhysicalNetwork> networks,
IEnumerable<Ipv4Route> routes, int? preferredIndex = null)
{
var candidates = networks.ToArray();
foreach (var route in routes.Where(r => r.Destination == "0.0.0.0" && r.Mask == "0.0.0.0")
.OrderBy(r => r.Metric).ThenBy(r => r.InterfaceIndex == preferredIndex ? 0 : 1).ThenBy(r => r.InterfaceIndex))
{
var network = candidates.FirstOrDefault(n => n.InterfaceIndex == route.InterfaceIndex);
if (network is not null && IPAddress.TryParse(route.NextHop, out var gateway))
return network with { Ipv4Gateway = gateway };
}
return null;
}
}