检查OpenVPN UDP端口是否已打开

时间:2014-01-30 16:42:51

标签: c# .net udp openvpn udpclient

我想检查OpenVPN的udp端口是否打开。 对于Tcp Port,它非常简单,但现在我在使用Udp端口。

这是我的TCP实施

private static bool TestConnectionInternal(string hostname, int port, int timeOutMs, int maxTries, int count)
{
    using (var tcpClient = new TcpClient())
    {
        try
        {
            Task result = tcpClient.ConnectAsync(hostname, port);
            return result.Wait(timeOutMs);

        }
        catch (Exception e)
        {
            count += 1;
            if (count < maxTries)
            {
                return TestConnectionInternal(hostname, port, timeOutMs, maxTries, count);
            }
            return false;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

无法知道UDP端口是否已打开。如果幸运的话,你得到一个icmp无法访问的端口关闭否定答案。对于某些协议(如NTP),您可以尝试发送有效查询并检查响应。如果使用--tls-auth或--secret配置OpenVPN,如果您不知道密钥,则无法生成有效的数据包来触发repsonse。

答案 1 :(得分:1)

简单检查OpenVPN UDP服务(除了使用--tls-auth或--secret)

bool CheckOpenVPNudp(string ip, int port)
        {
            IPEndPoint RemoteEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            byte[] data = { 56, 1, 0, 0, 0, 0, 0, 0, 0 }; //OpenVPN client welcome datagram
            server.SendTo(data, data.Length, SocketFlags.None, RemoteEndPoint);
            server.ReceiveTimeout = 15000; //15 seconds timeout
            EndPoint Remote = (EndPoint)(RemoteEndPoint);
            try
            {
                byte[] answer = new byte[1024];
                int recv = server.ReceiveFrom(answer, ref Remote);
                Console.WriteLine("Message received from {0}:", Remote.ToString());
                Console.WriteLine(System.Text.Encoding.ASCII.GetString(answer, 0, recv));
                return true;

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return false;
            }

        }