小弟用winform做一个局域网聊天工具,想要自动连接对方的电脑,代码如下:
IPAddress IP = Dns.GetHostAddresses(Dns.GetHostName())[0];
string[] IParry = IP.ToString().Split('.');
tcpCilent = new TcpClient();
for (int i = 1; i <= 255; i++)
{
     try
     {
          tcpCilent.Connect(IParry[0] + "." + IParry[1] + "." + IParry[2] + "." + i, 1234);     }
     catch (Exception ex)
     {
          MessageBox.Show(ex.Message);
     }
}
但如果没有这个IP就会很长时间后才会连接失败,我想有没有能直接ping某个ip的方法,如果ping的通的话就连接,这样就会快的多。
如果有这样的方法,请各位不吝赐教。

解决方案 »

  1.   

    http://dotnet.aspx.cc/ShowDetail.aspx?id=VXMGWMHF-OJCC-4RBD-KH6X-RIJQLD17QMFW
      

  2.   

                Process p = new Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = true;
                p.Start();
                p.StandardInput.WriteLine("ping -n 1 " + getserverip);
                p.StandardInput.WriteLine("exit");
                string strRst = p.StandardOutput.ReadToEnd();
                string str = "Received = 1";
                isping = strRst.Contains(str);
                p.Close();
      

  3.   

    首先Ping方法并不能有效得知对方在线1,不确定对方在线
    2,不确定对方开了防火墙禁止了Ping。用UDP试试,广播协议,根据端口,对方端口会有响应,然后就可以连接。
      

  4.   

    XP系统记得要将对方的防火墙关闭或开通对应的端口.还有,我用VS.NET2003写的,UDP连接,用IP地址连接会很慢,用电脑名连接的会很快.( 或者我说反了,你试试:) )