C# 网络状况确认工具(Ping)

网络状况确认工具
主要包括:HostTransforIP、PingHost、PingPort、PingServer

1 HostTransforIP

private IPAddress HostTransforIP(string host)
{
  string ipString;
  try
  {
    ipString = new IPEndPoint(Dns.GetHostEntry(host).AddressList[0], 0).Address.ToString();
  }
  catch (Exception ex)
  {
    this.showMsg("DNS Exception:" + (object) ex);
    throw new Exception("DNS Exception:" + (object) ex);
  }
  return IPAddress.Parse(ipString);
}

2 PingHost

    private void PingHost(string host)
    {
      try
      {
        Process process = new Process();
        process.StartInfo.Arguments = host;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.CreateNoWindow = true;
        process.StartInfo.FileName = "ping.exe";
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.Start();
        string end = process.StandardOutput.ReadToEnd();
        process.Close();
      }
      catch (Exception ex)
      {
        this.showMsg("PingHost Host Exception:" + (object) ex);
        throw new Exception("PingHost Exception:" + (object) ex);
      }
    }

3 PingPort

    private void PingPort(string host, int port)
    {
      try
      {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        IPAddress ip = this.transforHostToIP(host);
        if (ip == null)
          return;
        IPEndPoint ipEndPoint = new IPEndPoint(ip, port);
        using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
        {
          socket.Connect((EndPoint) ipEndPoint);
          stopwatch.Stop();
        }
      }
      catch (Exception ex)
      {
        throw new Exception("PingPort Exception:" + (object) ex);
      }
    }

4 PingServer

private void PingServer(string uri)
    {
      try
      {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        // ISSUE: variable of a compiler-generated type
        XMLHTTP instance = (XMLHTTP) Activator.CreateInstance(System.Type.GetTypeFromCLSID(new Guid("F6D90F16-9C73-11D3-B32E-00C04F990BB4")));
        string bstrUrl = uri + "LoginServiceMtom.svc";
        // ISSUE: reference to a compiler-generated method
        instance.open("GET", bstrUrl, (object) false, (object) null, (object) null);
        // ISSUE: reference to a compiler-generated method
        instance.send((object) bstrUrl);
        int status = instance.status;
        stopwatch.Stop();
        if (status == 200)
        {
          this.showMsg("PingServer 終了(" + stopwatch.ElapsedMilliseconds.ToString() + "ms)");
        }
        else
        {
          throw new Exception("PingServer Err status:" + status.ToString());
        }
      }
      catch (Exception ex)
      {
        throw new Exception("PingServer Exception:" + (object) ex);
      }
    }

你可能感兴趣的:(C#)