網路可用性

System.Net.NetworkInformation 命名空間可讓您收集網路事件、變更、統計資料和屬性的相關資訊。 在本文中,您將了解如何使用 System.Net.NetworkInformation.NetworkChange 類別來判斷網路位址或可用性是否已變更。 此外,您會看到有關介面或通訊協定的網路統計資料和屬性。 最後,您將使用 System.Net.NetworkInformation.Ping 類別來判斷遠端主機是否可以連線。

網路變更事件

System.Net.NetworkInformation.NetworkChange 類別可讓您判斷網路位址或可用性是否已變更。 若要使用此類別,請建立事件處理常式來處理變更,並將它與 NetworkAddressChangedEventHandlerNetworkAvailabilityChangedEventHandler 建立關聯。

NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged;

static void OnNetworkAvailabilityChanged(
    object? sender, NetworkAvailabilityEventArgs networkAvailability) =>
    Console.WriteLine($"Network is available: {networkAvailability.IsAvailable}");

Console.WriteLine(
    "Listening changes in network availability. Press any key to continue.");
Console.ReadLine();

NetworkChange.NetworkAvailabilityChanged -= OnNetworkAvailabilityChanged;

在上述 C# 程式碼中:

  • 註冊 NetworkChange.NetworkAvailabilityChanged 事件的事件處理常式。
  • 事件處理常式只會將可用性狀態寫入主控台。
  • 訊息會寫入主控台,讓使用者知道程式碼正在接聽網路可用性的變更,並等候按下按鍵以結束。
  • 取消註冊事件處理常式。
NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged;

static void OnNetworkAddressChanged(
    object? sender, EventArgs args)
{
    foreach ((string name, OperationalStatus status) in
        NetworkInterface.GetAllNetworkInterfaces()
            .Select(networkInterface =>
                (networkInterface.Name, networkInterface.OperationalStatus)))
    {
        Console.WriteLine(
            $"{name} is {status}");
    }
}

Console.WriteLine(
    "Listening for address changes. Press any key to continue.");
Console.ReadLine();

NetworkChange.NetworkAddressChanged -= OnNetworkAddressChanged;

在上述 C# 程式碼中:

網路統計資料和屬性

您可以根據介面或通訊協定來收集網路統計資料和屬性。 NetworkInterfaceNetworkInterfaceTypePhysicalAddress 類別提供特定網路介面的相關資訊,而 IPInterfacePropertiesIPGlobalPropertiesIPGlobalStatisticsTcpStatisticsUdpStatistics 類別提供第 3 層和第 4 層封包的相關資訊。

ShowStatistics(NetworkInterfaceComponent.IPv4);
ShowStatistics(NetworkInterfaceComponent.IPv6);

static void ShowStatistics(NetworkInterfaceComponent version)
{
    var properties = IPGlobalProperties.GetIPGlobalProperties();
    var stats = version switch
    {
        NetworkInterfaceComponent.IPv4 => properties.GetTcpIPv4Statistics(),
        _ => properties.GetTcpIPv6Statistics()
    };

    Console.WriteLine($"TCP/{version} Statistics");
    Console.WriteLine($"  Minimum Transmission Timeout : {stats.MinimumTransmissionTimeout:#,#}");
    Console.WriteLine($"  Maximum Transmission Timeout : {stats.MaximumTransmissionTimeout:#,#}");
    Console.WriteLine("  Connection Data");
    Console.WriteLine($"      Current :                  {stats.CurrentConnections:#,#}");
    Console.WriteLine($"      Cumulative :               {stats.CumulativeConnections:#,#}");
    Console.WriteLine($"      Initiated  :               {stats.ConnectionsInitiated:#,#}");
    Console.WriteLine($"      Accepted :                 {stats.ConnectionsAccepted:#,#}");
    Console.WriteLine($"      Failed Attempts :          {stats.FailedConnectionAttempts:#,#}");
    Console.WriteLine($"      Reset :                    {stats.ResetConnections:#,#}");
    Console.WriteLine("  Segment Data");
    Console.WriteLine($"      Received :                 {stats.SegmentsReceived:#,#}");
    Console.WriteLine($"      Sent :                     {stats.SegmentsSent:#,#}");
    Console.WriteLine($"      Retransmitted :            {stats.SegmentsResent:#,#}");
    Console.WriteLine();
}

在上述 C# 程式碼中:

判斷是否可以連線遠端主機

您可以使用 Ping 類別,判斷網路上的遠端主機是否啟動且可連線。

using Ping ping = new();

string hostName = "stackoverflow.com";
PingReply reply = await ping.SendPingAsync(hostName);
Console.WriteLine($"Ping status for ({hostName}): {reply.Status}");
if (reply is { Status: IPStatus.Success })
{
    Console.WriteLine($"Address: {reply.Address}");
    Console.WriteLine($"Roundtrip time: {reply.RoundtripTime}");
    Console.WriteLine($"Time to live: {reply.Options?.Ttl}");
    Console.WriteLine();
}

在上述 C# 程式碼中:

另請參閱