如何知道一台机器是否可以用c# ping通?

How to know if a machine can be pinged with c#?

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

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

你可以发个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;
    }
}

使用System.Net.Networkinformation.Ping.Send(...).

您可以通过多种方式使用 Ping,包括指定主机名,在这种情况下 the MSDN sample 是:

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);
    }
}

或者您可以指定一个 IPAddress, in which case the MSDN sample 是:

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);
    }
}

为了知道一台机器是否能被ping通;需要允许 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;
    }