2010-05-14 141 views
3

我需要轮询运行某些专有软件的服务器以确定此服务是否正在运行。使用wireshark,我已经能够缩小它使用的TCP端口,但看起来流量是加密的。确定服务器是否在给定端口上侦听

在我的情况下,如果服务器正在接受连接(即telnet serverName 1234),那么服务启动并且一切正常。换句话说,我不需要做任何实际的数据交换,只需打开一个连接然后安全地关闭它。

我想知道如何用C#和套接字来模拟这个。我的网络编程基本上以WebClient结束,所以这里的任何帮助都非常感谢。

回答

6

该过程其实很简单。

using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) 
{ 
    try 
    { 
     socket.Connect(host, port); 
    } 
    catch (SocketException ex) 
    { 
     if (ex.SocketErrorCode == SocketError.ConnectionRefused) 
     { 
      // ... 
     } 
    } 
} 
+0

有没有办法调整连接超时?它似乎失败了,但只有大约一分钟后... – Nate 2010-05-14 18:51:06

+0

@Nate我相信这是多久的过程。没有连接超时选项。 – ChaosPandion 2010-05-14 18:57:23

+0

我加了'if(ex.SocketErrorCode == SocketError.ConnectionRefused || ex.SocketErrorCode == SocketError.TimedOut)' – Nate 2010-05-14 19:00:26

0

使用TcpClient类连接服务器。

3

只要使用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; 
    } 
} 
+0

有没有办法调整连接超时?它似乎失败了,但只有大约一分钟后...... – Nate 2010-05-14 18:51:36

2

我已经使用了下面的代码。有一个警告......在高事务环境中,客户端的可用端口可能会耗尽,因为这些套接字不是由操作系统以.NET代码发布的相同速率释放的。

如果有人有更好的主意,请发帖。我发现服务器无法再传出连接时会出现雪球问题。我正在寻找更好的解决方案...

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; 
相关问题