在C#中使用平 [英] Using ping in c#

查看:124
本文介绍了在C#中使用平的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我平用C#它说,成功当我平安与Windows远程系统它说,有没有回答,只是。 Windows是正确的,该设备未连接。为什么我的code能够成功地ping时,Windows是不是?

下面是我的code:

 平P1 =新平();
PingReply PR = p1.Send(192.168.2.18);
//检查时,ping命令成功
而(!PR.Status.ToString()。等于(成功))
{
    Console.WriteLine(PR.Status.ToString());
    PR = p1.Send(192.168.2.18);
}
//检查后平为n成功
而(PR.Status.ToString()。等于(成功))
{
    Console.WriteLine(PR.Status.ToString());
    PR = p1.Send(192.168.2.18);
}


解决方案

 公共静态布尔PingHost(字符串nameOrAddress)
{
    布尔可侦测= FALSE;
    平瓶儿=新平();
    尝试
    {
        PingReply回复= pinger.Send(nameOrAddress);
        可侦测= reply.Status == IPStatus.Success;
    }
    赶上(PingException)
    {
        //放弃PingExceptions和返回false;
    }
    返回ping的;
}

When I Ping a remote system with windows it says there is no reply, but when I ping with c# it says success. Windows is correct, the device is not connected. Why is my code able to successfully ping when Windows is not?

Here is my code :

Ping p1 = new Ping();
PingReply PR = p1.Send("192.168.2.18");
// check when the ping is not success
while (!PR.Status.ToString().Equals("Success"))
{
    Console.WriteLine(PR.Status.ToString());
    PR = p1.Send("192.168.2.18");
}
// check after the ping is n success
while (PR.Status.ToString().Equals("Success"))
{
    Console.WriteLine(PR.Status.ToString());
    PR = p1.Send("192.168.2.18");
}

解决方案

public static bool PingHost(string nameOrAddress)
{
    bool pingable = false;
    Ping pinger = new Ping();
    try
    {
        PingReply reply = pinger.Send(nameOrAddress);
        pingable = reply.Status == IPStatus.Success;
    }
    catch (PingException)
    {
        // Discard PingExceptions and return false;
    }
    return pingable;
}

这篇关于在C#中使用平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆