命名空間 System.Net.NetworkInformation 可讓您收集網路事件、變更、統計數據和屬性的相關信息。 在本文中,您將瞭解如何使用 類別 System.Net.NetworkInformation.NetworkChange 來判斷網路位址或可用性是否已變更。 此外,您可以根據介面或通訊協議查看網路統計數據和屬性。 最後,您將使用 類別 System.Net.NetworkInformation.Ping 來判斷遠端主機是否可連線。
網路變更事件
類別 System.Net.NetworkInformation.NetworkChange 可讓您判斷網路位址或可用性是否已變更。 若要使用此類別,請建立事件處理程式來處理變更,並將它與 NetworkAddressChangedEventHandler 或 NetworkAvailabilityChangedEventHandler產生關聯。
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# 程式代碼:
- 註冊NetworkChange.NetworkAddressChanged事件的事件處理程式。
- 事件處理程式會逐一查看 NetworkInterface.GetAllNetworkInterfaces(),並將其名稱和作狀態寫入主控台。
- 訊息會寫入主控台,讓使用者知道程式正在監聽網路可用性的變化,並等候按下任意鍵以結束。
- 取消註冊事件處理程式。
網路統計數據和屬性
您可以收集介面或通訊協定上的網路統計數據和屬性。 NetworkInterface、 NetworkInterfaceType和 PhysicalAddress 類別會提供特定網路介面的相關信息,而IPInterfaceProperties、IPGlobalPropertiesIPGlobalStatisticsTcpStatistics 、 和 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# 程式代碼:
- 呼叫自定義
ShowStatistics方法以顯示每個通訊協定的統計數據。 - 方法會呼叫
ShowStatistics和 IPGlobalProperties.GetIPGlobalProperties(),並根據指定的 NetworkInterfaceComponent,進一步呼叫 IPGlobalProperties.GetIPv4GlobalStatistics() 或 IPGlobalProperties.GetIPv6GlobalStatistics()。 - TcpStatistics 會被寫入主控台。
判斷遠端主機是否可連線
您可以使用 類別 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# 程式代碼:
- 實例化 Ping 物件。
- 使用Ping.SendPingAsync(String)主機名參數呼叫
"stackoverflow.com"。 - Ping 的狀態會寫入主控台。