C#如何监测某台机器网络连接是否畅通?

解决方案 »

  1.   

      这一方面我有一点理解,不过没做过。可以用PING机制。它只能检测连通。具体就用Socket class中的raw socket功能,发送一个ICMP报文。
      

  2.   

     Ping pingSender = new Ping();
                PingOptions options = new PingOptions();            // Use the default Ttl value which is 128,
                // but change the fragmentation behavior.
                options.DontFragment = true;            // Create a buffer of 32 bytes of data to be transmitted.
                string data = "aaa";
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 120;
                PingReply reply = pingSender.Send("222.111.111.111", timeout, buffer, options);
                if (reply.Status == IPStatus.Success)
                {
                    i = 0;
                    Console.WriteLine("IP地址: {0}", reply.Address.ToString());
                    Console.WriteLine("返回时间: {0}", reply.RoundtripTime);
                }
    看返回时间
      

  3.   

    如果是判断本机是否连通的话,可以调用API
    [DllImport("wininet.dll")]
    private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
    /// <summary>
    /// 获取机器是否连接上网络
    /// </summary>
    public static bool IsConnected
    {
           get
           {
                int Desc;
                return InternetGetConnectedState(out Desc, 0);
            }
    }
    如果是判断其他的机器是否能连上本机,可以用Ping这个类
    Ping pingServer = new Ping();
    PingReply reply = pingServer.Send("目标机器的名称或ip");
    if (reply.Status == IPStatus.Success)
    {
        //连接成功
    }