小弟用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的通的话就连接,这样就会快的多。
如果有这样的方法,请各位不吝赐教。
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的通的话就连接,这样就会快的多。
如果有这样的方法,请各位不吝赐教。
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();
2,不确定对方开了防火墙禁止了Ping。用UDP试试,广播协议,根据端口,对方端口会有响应,然后就可以连接。