Как получить адрес шлюза по умолчанию на C# — методы для Windows и Linux

Чтобы получить адрес шлюза по умолчанию в C#, вы можете использовать разные методы в зависимости от операционной системы и конфигурации сети. Вот несколько методов, которые вы можете использовать:

Метод 1: использование класса NetworkInterface (Windows и Linux)

using System.Net.NetworkInformation;
public static string GetDefaultGateway()
{
    string gateway = null;
    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        if (nic.OperationalStatus == OperationalStatus.Up)
        {
            GatewayIPAddressInformationCollection gatewayAddresses = nic.GetIPProperties().GatewayAddresses;
            if (gatewayAddresses.Count > 0)
            {
                gateway = gatewayAddresses[0].Address.ToString();
                break;
            }
        }
    }
    return gateway;
}

Метод 2: использование класса ManagementObjectSearcher (Windows)

using System.Management;
public static string GetDefaultGateway()
{
    string gateway = null;
    ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
    foreach (ManagementObject mo in mos.Get())
    {
        if (mo["DefaultIPGateway"] != null)
        {
            gateway = ((string[])mo["DefaultIPGateway"])[0];
            break;
        }
    }
    return gateway;
}

Метод 3: использование команд оболочки (Linux)

using System.Diagnostics;
public static string GetDefaultGateway()
{
    string gateway = null;
    Process process = new Process();
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.FileName = "/sbin/ip";
    startInfo.Arguments = "route show default";
    startInfo.RedirectStandardOutput = true;
    startInfo.UseShellExecute = false;
    startInfo.CreateNoWindow = true;
    process.StartInfo = startInfo;
    process.Start();
    string output = process.StandardOutput.ReadToEnd();
    process.WaitForExit();
    string[] lines = output.Split('\n');
    if (lines.Length >= 1)
    {
        string[] fields = lines[0].Split(' ');
        gateway = fields[fields.Length - 2];
    }
    return gateway;
}

Эти методы подходят как для Windows, так и для Linux. Метод 1 и метод 2 предназначены только для Windows, а метод 3 — для Linux.