【问题标题】:How to check if a computer is responding from C#如何检查计算机是否从 C# 响应
【发布时间】:2008-12-07 13:31:11
【问题描述】:

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

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

【问题讨论】:

  • 你需要连接什么端口?考虑到防火墙——网络范围和每个系统——一个系统很容易可用,但如果你选择了错误的端口来尝试,它似乎没有响应。
  • 顺便说一句,我只想说,当涉及到网络时,定义上不存在“确定性”方法。 en.wikipedia.org/wiki/Deterministic_algorithm

标签: c# networking netbios


【解决方案1】:

简单!使用 System.Net.NetworkInformation 命名空间的 ping 工具!

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

【讨论】:

  • 出于安全原因,PING 是在我们的网络边界被阻止的服务之一——以及各种其他端口。如果可用,这是一个很好的机制,但您必须知道它是否会首先工作,并且将来不会关闭。
  • 事实上,这可能发生在任何服务上。因此,如果您需要可靠的方式来访问远程计算机上的服务,您可能应该考虑在更高级别的协议(您特别依赖的协议)上检查它。
【解决方案2】:

要检查已知服务器上的特定 TCP 端口 (myPort),请使用以下 sn-p。您可以捕获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。

【讨论】:

    【解决方案3】:

    只要您想检查自己子网内的计算机,就可以使用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

    【讨论】:

      猜你喜欢
      • 2015-06-02
      • 1970-01-01
      • 2014-12-28
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多