5

检查计算机是否处于活动状态并做出响应(例如在 ping/NetBios 中)的最简单方法是什么?我想要一种可以限制时间的确定性方法。

一种解决方案是在单独的线程中简单地访问共享 (File.GetDirectories(@"\compname")),如果花费的时间过长,则终止该线程。

4

3 回答 3

10

简单的!使用System.Net.NetworkInformation命名空间的 ping 功能!

http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx

于 2008-12-07T13:42:33.600 回答
3

要检查已知服务器上的特定 TCP 端口 ( myPort),请使用以下代码段。您可以捕获System.Net.Sockets.SocketException异常以指示不可用的端口。

using System.Net;
using System.Net.Sockets;
...

IPHostEntry myHostEntry = Dns.GetHostByName("myserver");
IPEndPoint host = new IPEndPoint(myHostEntry.AddressList[0], myPort);

Socket s = new Socket(AddressFamily.InterNetwork,
    SocketType.Stream, ProtocolType.Tcp);
s.Connect(host);

此外,专门的检查可以在套接字上尝试 IO 超时。

于 2008-12-07T14:16:11.770 回答
1

只要您想检查自己子网内的计算机,您就可以使用ARP检查它。这是一个例子:

    //for sending an arp request (see pinvoke.net)
    [DllImport("iphlpapi.dll", ExactSpelling = true)]
    public static extern int SendARP(
                                        int DestIP, 
                                        int SrcIP, 
                                        byte[] pMacAddr, 
                                        ref uint PhyAddrLen);


    public bool IsComputerAlive(IPAddress host)
    {
        //can't check the own machine (assume it's alive)
        if (host.Equals(IPAddress.Loopback))
            return true;

        //Prepare the magic

        //this is only needed to pass a valid parameter
        byte[] macAddr = new byte[6];
        uint macAddrLen = (uint)macAddr.Length;

        //Let's check if it is alive by sending an arp request
        if (SendARP((int)host.Address, 0, macAddr, ref macAddrLen) == 0)
            return true; //Igor it's alive!

        return false;//Not alive
    }

有关详细信息,请参阅Pinvoke.net

于 2012-05-04T13:33:23.067 回答