共用方式為


網路可用性

命名空間 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 類別會提供特定網路介面的相關信息,而IPInterfacePropertiesIPGlobalPropertiesIPGlobalStatisticsTcpStatistics 、 和 UdpStatistics 類別則提供第 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# 程式代碼:

另請參閱