我需要轮询一个运行了某些专有软件的服务器,以确定该服务是否正在运行。使用wireshark,我已经能够缩小它使用的TCP端口,但似乎流量是加密的。
在我的情况下,如果服务器接受连接(即telnet serverName 1234),那么很有把握该服务已启动,一切正常。换句话说,我不需要进行任何实际数据交换,只需打开一个连接,然后安全地关闭它。
我想知道如何使用C#和Sockets来模拟这种情况。我的网络编程基本上以WebClient结束,所以在这里任何帮助都将不胜感激。
我需要轮询一个运行了某些专有软件的服务器,以确定该服务是否正在运行。使用wireshark,我已经能够缩小它使用的TCP端口,但似乎流量是加密的。
在我的情况下,如果服务器接受连接(即telnet serverName 1234),那么很有把握该服务已启动,一切正常。换句话说,我不需要进行任何实际数据交换,只需打开一个连接,然后安全地关闭它。
我想知道如何使用C#和Sockets来模拟这种情况。我的网络编程基本上以WebClient结束,所以在这里任何帮助都将不胜感激。
这个过程实际上非常简单。
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
try
{
socket.Connect(host, port);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.ConnectionRefused)
{
// ...
}
}
}
只需使用 TcpClient
尝试连接服务器,如果连接失败,TcpClient.Connect 将抛出异常。
bool IsListening(string server, int port)
{
using(TcpClient client = new TcpClient())
{
try
{
client.Connect(server, port);
}
catch(SocketException)
{
return false;
}
client.Close();
return true;
}
}
public static bool IsServerUp(string server, int port, int timeout)
{
bool isUp;
try
{
using (TcpClient tcp = new TcpClient())
{
IAsyncResult ar = tcp.BeginConnect(server, port, null, null);
WaitHandle wh = ar.AsyncWaitHandle;
try
{
if (!wh.WaitOne(TimeSpan.FromMilliseconds(timeout), false))
{
tcp.EndConnect(ar);
tcp.Close();
throw new SocketException();
}
isUp = true;
tcp.EndConnect(ar);
}
finally
{
wh.Close();
}
}
}
catch (SocketException e)
{
LOGGER.Warn(string.Format("TCP connection to server {0} failed.", server), e);
isUp = false;
}
return isUp;
if(ex.SocketErrorCode == SocketError.ConnectionRefused || ex.SocketErrorCode == SocketError.TimedOut)
。 - Nate