/// <summary>
/// 检查服务器和端口是否可以连接
/// </summary>
/// <param name="ipString">服务器ip</param>
/// <param name="port">端口</param>
/// <returns></returns>
public static bool CheckConnect(string ipString, int port)
{
bool right =false;
System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient()
{ SendTimeout = 1000 };
IPAddress ip = IPAddress.Parse(ipString);
try
{
var result = tcpClient.BeginConnect(ip, port, null, null);
var back = result.AsyncWaitHandle.WaitOne(2000);
right = tcpClient.Connected;
}
catch (Exception ex)
{
//LogHelpter.AddLog($"连接服务{ipString}:{port}失败,设置的超时时间{tcpClient.SendTimeout}毫秒");
//连接失败
return false;
}
tcpClient.Close();
tcpClient.Dispose();
return right;
}
C#检查服务器ip和端口是否通畅,是否可访问
于 2021-03-03 09:40:20 首次发布