如何知道机器是否可以使用c#进行ping操作?

时间:2016-12-06 10:09:06

标签: c# ping

我正在尝试测试我的机器是否可以被其他网络实体ping:

Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType);
string allowed = mgr.LocalPolicy.CurrentProfile.IcmpSettings.AllowInboundEchoRequest;

3 个答案:

答案 0 :(得分:0)

您可以发送ping以检查是否可以ping通:

public static bool CanBePinged(string hostname)
{
    if (string.IsNullOrWhiteSpace(hostname)) throw new ArgumentException("hostname");

    Ping p1 = new Ping();
    try
    {
        PingReply PR = p1.Send(hostname);
        return PR.Status == IPStatus.Success;
    }catch(Exception e)
    {
        return false;
    }
}

答案 1 :(得分:0)

使用PEP 506 .Send(...)

您可以通过多种方式使用Ping,包括指定主机名,在这种情况下System.Net.Networkinformation.Ping是:

public static void SimplePing ()
{
    Ping pingSender = new Ping ();
    PingReply reply = pingSender.Send ("www.contoso.com");

    if (reply.Status == IPStatus.Success)
    {
        Console.WriteLine ("Address: {0}", reply.Address.ToString ());
        Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
        Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
        Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
        Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
    }
    else
    {
        Console.WriteLine (reply.Status);
    }
}

或者您可以指定the MSDN sample,在这种情况下IPAddress是:

public static void LocalPing ()
{
    // Ping's the local machine.
    Ping pingSender = new Ping ();
    IPAddress address = IPAddress.Loopback;
    PingReply reply = pingSender.Send (address);

    if (reply.Status == IPStatus.Success)
    {
        Console.WriteLine ("Address: {0}", reply.Address.ToString ());
        Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
        Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
        Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
        Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
    }
    else
    {
        Console.WriteLine (reply.Status);
    }
}

答案 2 :(得分:0)

为了知道机器是否可以被钉住;需要允许ICMP类型8输入和输出0。

public Boolean IsPingable()
    {
        Boolean icmpAllowed = false;
        INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType);
        Object allowedin8 = null;
        Object restrictedin8 = null;
        Object allowedout0 = null;
        Object restrictedout0 = null;
      mgr.IsIcmpTypeAllowed(NET_FW_IP_VERSION_.NET_FW_IP_VERSION_V4,"127.0.0.1", 0, out allowedin0, out restrictedin0);
      mgr.IsIcmpTypeAllowed(NET_FW_IP_VERSION_.NET_FW_IP_VERSION_V4, "8.8.8.8", 8, out allowedout8, out restrictedout8);
        if ((Boolean)allowedin0 && (Boolean)allowedout8)
        {
            icmpAllowed = true;
        }
        return icmpAllowed;
    }