通过C#调取cmd检查Telnet的链接状态时,发现无法收到任何返回,究其原因是因为传统的ipconfig/all指令是读取本地的数据,但是Telnet指令是建立一个socket连接,通过发送IP和HOST来校验端口连接情况,因此无法直接返回。经过研究,改用测试端口连通性的方式进行检查,代码如下
private string CheckTelnet(ref string result)
{
int port; //端口号
string host="" //IP地址
bool connect=false; //连接状态,默认为断开
string strlog=null;
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip,port);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(ipe);
}
catch(SocketException ex)
{
string result = ex.Message;
if(result.Contains("连接尝试失败"))
{
connect = false;
}
else
{
connect = true;
}
}
finally
{
clientSocekt.Close();
}
if(connect != true)
{
strlog="Telnet连接失败";
}
else
{
strlog="Telnet连接成功";
}
}