Opening a TCP socket from an Azure Website to an e

2019-07-11 08:01发布

问题:

Is it possible to open a TCP socket programmatically in C# from an Azure Website to an external server?

I have a need to check if another server is online - as ping cannot be used on Azure I was going to use TCP socket that the external server is configured to accept.

The code I have used locally works perfectly when pinging a public web server, however on Azure it doesn't work.

I'm aware that you can't ping due to the load balancer on Azure - but are opening TCP sockets out of the question too?

Can this be achieved? If not - how else can I check if an external server is alive without using a lengthy work around?

Note: There is definitely no firewall / port / IP issue with the external server.

This is my code that works on my local dev machine and on Rackspace

 public static bool TcpConnectivityTest(string ipAddress, int port = 1433, int timeoutMillisec = 2000)
    {
        Socket socket = null;

        try
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, false);

            var result = socket.BeginConnect(ipAddress, port, null, null);
            result.AsyncWaitHandle.WaitOne(timeoutMillisec, true);

            return socket.Connected;
        }
        catch
        {
            return false;
        }
        finally
        {
            if (null != socket)
            {
                socket.Close();
                socket.Dispose();
            }
        }
    }