tags:

views:

123

answers:

4

What's the best method to check if SQL server exists or not?

I'm trying Microsoft.SqlServer.Management.Smo.Server.PingSqlServerVersion() and it works fine if server exists and available. But it kinda pretty slow, if there is no such a server.

Is there any fast enough method to check without even defining user credentials (only the server name), if a server exists?

What do you recommend to use?

+1  A: 

You could try and open a tcp socket to port 1433 (default sql port) with a short timeout and see if it responds.

This requires the SQL server to have the TCP/IP protocol enabled.

Mikael Svenson
+1  A: 

To add to Mikael's, you could also ping the host first, as that will respond the quickest if the server is down.

Of course, this all assumes that you are trying to get to a remote server over TCP/IP.

Moose
+1  A: 

You could just use TcpClient class to query the server and check if a specific port is open, could be something like this:

using System.Net;
using System.Net.Sockets;

public bool CheckServerAvailablity(string serverIPAddress, int port)
{
  try
  {
    IPHostEntry ipHostEntry = Dns.Resolve(serverIPAddress);
    IPAddress ipAddress = ipHostEntry.AddressList[0];

    TcpClient TcpClient = new TcpClient();
    TcpClient.Connect(ipAddress , port);
    TcpClient.Close();

    return true;
  }
  catch
  {
    return false;
  }
} 
armannvg
+1  A: 

You could still use Microsoft.SqlServer.Management.Smo.Server.PingSqlServerVersion() but use it asynchronously. e.g. you could call it via a BackWorker class. The DoWork event would call Microsoft.SqlServer.Management.Smo.Server.PingSqlServerVersion(). The RunWorkerCompleted would just set a boolean variable to true. THat way you could fire it off, wait however long you wanted, check the boolean value and if it was not true then you would know that the SQL server had not responded yet and you could cancel the BackgroundWorker.

Ben Robinson