我如何处理 C# 中的 Ping 异常

How Can i Deal with Ping Exception in c#

我创建了一个简单的方法来检查我的 Internet 连接是否有效。不幸的是,由于 System.Net.Ping.dll 中的 System.Net.NetworkInformation.PingException”,try 部分被忽略了。众所周知,问题出现在 PingReply 上。 你能告诉我如何处理这个异常并允许代码正确 运行 以便执行 try 部分。

我的函数:

    private void ConnectionStatusChecker(object source, ElapsedEventArgs e)
    {

        Ping myPing = new Ping();
        String host = "https://www.google.com/";
        byte[] buffer = new byte[32];
        int timeout = 1000;
        PingOptions pingOptions = new PingOptions();

        Ping ping = new Ping();
        try
        {
            PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
            if (reply.Status == IPStatus.Success)
                ConnectionStatus = "Connected";
            else
                ConnectionStatus = "Disconnected";
        }
        catch (System.Net.NetworkInformation.PingException)
        {
            ConnectionStatus = "Disconnected-Exception";
        }
    }

编辑:我想在 ConnectionStatus 变量中存储有关我的 Internet 连接的信息。 Try 部分描述了断开或连接时的值。但是 PingException 不允许我检查它 - 异常会自动阻止 try 部分。问题是,如何处理这个异常,我犯的错误或来源在哪里?

您应该登录 InnerException 以查看实际情况:

catch (PingException ex)
{
    Console.WriteLine(ex.InnerException);
    ConnectionStatus = "Disconnected-Exception";
}

输出以下输出:

System.Net.Sockets.SocketException (11001): No such host is known.
   at System.Net.Dns.InternalGetHostByName(String hostName)
   at System.Net.Dns.GetHostAddresses(String hostNameOrAddress)
   at System.Net.NetworkInformation.Ping.GetAddressAndSend(String hostNameOrAddress, Int32 timeout, Byte[] buffer, PingOptions options)

并且 ping 命令也失败(确保结果符合预期):

PS C:\Users\user> ping https://www.google.com/
Ping request could not find host https://www.google.com/. Please check the name and try again.

这意味着主机 https://www.google.com/ 没有为 HTTPS 启用 ICMP 回复。您可以查看 Can you get a reply from a HTTPS site using the Ping command? 以获得关于为什么会发生这种情况的良好解释。

您还可以在 System.Net.NetworkInformation.Ping.Send() 文档中验证这一点:

PingException

An exception was thrown while sending or receiving the ICMP messages. See the inner exception for the exact exception that was thrown.

改为尝试 ping 主机名 www.google.com:

Ping myPing = new Ping();
String host = "www.google.com";
byte[] buffer = new byte[32];
int timeout = 1000;
PingOptions pingOptions = new PingOptions();

string ConnectionStatus;

Ping ping = new Ping();
try
{
    PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
    if (reply.Status == IPStatus.Success)
        ConnectionStatus = "Connected";
    else
        ConnectionStatus = "Disconnected";
    }
catch (PingException ex)
{
    Console.WriteLine(ex.InnerException);
    ConnectionStatus = "Disconnected-Exception";
}

Console.WriteLine(ConnectionStatus);

无异常输出连接成功:

Connected