Ping导致未处理的异常

时间:2014-11-14 19:07:24

标签: c# .net-4.5 ping

我有一个服务器IP地址列表,在我的应用程序的一部分,在向每个服务器发送请求之前,我ping它。当我通过VS 2012测试它时,它会停止并在VS中显示一个页面,并说“#34;无法连接到远程服务器"”。我在try-catch中使用了ping,但它并没有落入异常部分;它只是执行ping.send()。其他一些ping超时,我抓住它们并显示正确的消息。当我检查异常跟踪(下面)时,它说:"无法建立连接,因为目标机器主动拒绝它"。有没有办法捕捉和处理这个而不是停止运行程序?

这是(部分)ping代码:

public static string PingServer(string host)
{
    PingOptions options = new PingOptions();
    options.DontFragment = true;
    Ping p = new Ping();
    PingReply reply = null;
    string NetworkMessage = string.Empty;

    try
    {
        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        byte[] buffer = Encoding.ASCII.GetBytes(data);
        int timeout = 120;
        Console.WriteLine(host);
        reply = p.Send(host, timeout, buffer, options);

这是例外追踪:

System.Net.WebException was unhandled
  HResult=-2146233079
  Message=Unable to connect to the remote server
  Source=System
  StackTrace:
       at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
       at PASSCrawlerNS.PASSCrawler.GetResponseCallback(IAsyncResult ar) in c:\Users\blah\Documents\Visual Studio 2012\Projects\test\test\Program.cs:line 102
       at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Net.ContextAwareResult.Complete(IntPtr userToken)
       at System.Net.HttpWebRequest.SetResponse(Exception E)
       at System.Net.ConnectionReturnResult.SetResponses(ConnectionReturnResult returnResult)
       at System.Net.Connection.CompleteConnectionWrapper(Object request, Object state)
       at System.Net.PooledStream.ConnectionCallback(Object owningObject, Exception e, Socket socket, IPAddress address)
       at System.Net.ServicePoint.ConnectSocketCallback(IAsyncResult asyncResult)
       at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
       at System.Net.ContextAwareResult.Complete(IntPtr userToken)
       at System.Net.Sockets.Socket.ConnectCallback()
       at System.Threading._ThreadPoolWaitOrTimerCallback.PerformWaitOrTimerCallback(Object state, Boolean timedOut)
  InnerException: System.Net.Sockets.SocketException
       HResult=-2147467259
       **Message=No connection could be made because the target machine actively refused it** 56.245.253.10:80
       Source=System
       ErrorCode=10061
       NativeErrorCode=10061
       StackTrace:
            at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
            at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
   InnerException: 

当我手动ping此服务器(56.245.253.10)时,它会回复。

1 个答案:

答案 0 :(得分:1)

如果您只是想通过ping方法测试服务器是否处于活动状态,您可以试试这个

    private async Task<bool> PingHost(string ip)
    {
        bool pingable = true;
        Ping mypinger = new Ping();
        try
        {
            PingReply reply = mypinger.Send(ip);
            pingable = (reply.Status == IPStatus.Success) ? true : false;
        }
        catch (PingException)
        {
            return false;
        }
        return pingable;
    }

它以异步方式运行,因此不会阻止您的主线程。您必须使用来自另一个异步方法的await运算符来调用它