Click here to Skip to main content
15,867,488 members
Articles / Database Development / SQL Server
Article

Locate SQL Server instances on the local network

Rate me:
Please Sign up or sign in to vote.
4.80/5 (46 votes)
24 Nov 2005CPOL6 min read 306.9K   5K   139   60
An article on locating MS SQL Server instances on the local network, and retrieving information about them.

Introduction

This articles shows how to retrieve a list of PCs on the local network which are running MS SQL Server, and gets information about the instances, such as server name, instance name, version, and databases.

Background

To get a list of the nearby SQL Servers is as simple as typing "osql /L" on a command prompt. But getting them programmatically, for use inside an application, is a bit trickier. The most common use for this would be to create a connection string building form in managed code, which will be the subject of my next article.

Note also, that while the subject matter is SQL Server, the first half of this article deals mostly with sockets.

To create a list of SQL Server instances, I first tried several different methods, all of which had two things in common: they took a very long time, and they were only marginally successful at finding SQL Servers instances on the network. Eventually, I had the idea of running "osql -L" with a packet sniffer running (I used Ethereal), to see how osql was doing it.

Its method was to send out a Broadcast UDP packet on port 1434, with the contents of just a byte of 0x02, to which each server would respond. Sending such a message is quite simple:

C#
Socket socket = new Socket(AddressFamily.InterNetwork, 
              SocketType.Dgram, ProtocolType.Udp );
//  For .Net v 1.1 the options are cumbersome & hidden.
    socket.SetSocketOption(SocketOptionLevel.Socket, 
              SocketOptionName.Broadcast, 1);
    socket.SetSocketOption(SocketOptionLevel.Socket, 
              SocketOptionName.ReceiveTimeout, 3000);
    
//  For .Net v 2.0 it's a bit simpler
//  socket.EnableBroadcast = true;    // for .Net v2.0
//  socket.ReceiveTimeout = 3000;     // for .Net v2.0

IPEndPoint ep = new IPEndPoint(IPAddress.Broadcast, 1434);
byte[] msg = new byte[] { 0x02 };
socket.SendTo(msg, ep);

It's vitally important that you set the timeout. Without it, the Receive method will just keep waiting (forever!) until it gets something. However, since we'll be waiting for responses from an unknown number of servers, we have to decide to give up at some point. I've set that point, initially, at 3 seconds. Before I realized that the Broadcast & Timeout options were available (but hidden) on the Socket class, I had this elaborate class which derived from UdpClient and implemented asynchronous receiving.

As it turns out, with the proper options set, getting a response is as simple as you'd hope.

C#
byte[] bytBuffer = new byte[256];
socket.Receive(bytBuffer);

The Receive method will get the response from one server, so we'll have to put that code in a loop to get all of them. Of course, once we've gotten a response, we need to interpret it. For this, I've created a simple class called SqlServerInfo, which I'll explain further in a minute.

After we've received, processed and stored the response, we just keep looping until we don't get a response within the timeout. The downside of using a timeout, is that when it is reached, the Socket throws a SocketException, which means we have to incur the overhead time to process a throw every time we call this method. This is in addition to the timeout delay itself. I was able to find a way to minimize this.

I initially set the timeout to 3 seconds. The problem here was that after each response, I'd call Receive again, and the timeout timer would start over. So the total time for the method would be: the total actual processing time + the timeout + the throw overhead. This was about 5 seconds in my tests. This seems way too long to me -- remember, this is something we are going to want to do in the Page_Load of a form. One thing I noticed was that after I send the broadcast message, there would be a short delay as the message went out, the remote servers received it and prepared their responses. However, after that delay, all the responses would come in a pack. So, I decided, after I processed the first response, to reset the timeout to 0.3 seconds. This cut the total time down to about 1-2 seconds, a much more reasonable delay. (However, if there were no servers at all on the network, it would still take 3+ seconds to realize that.)

Now, back to interpreting the response we've gotten, which is quite simple. The first three bytes are a byte of 0x05, followed by two bytes giving the length of the rest which is straight ASCII text of pairs of items, separated by semicolons:

data item 1 name ; data item 1 value ; data item 2 name  ; data item 2 value;

or more specifically:

ServerName;DATA001;InstanceName;MSSQLSERVER;IsClustered;No;Version;8.00.194;tcp;1433

To make use of this, we'll have to convert from a byte array of ASCII characters to a .NET string of UNICODE characters, which the framework is nice enough to provide a method for (although it does bury in under System.Text.ASCIIEncoding.ASCII). Then, separate the parts, and move the the data values to properties where they can be accessed easier.

Of course, while the information provided in the broadcast response is useful, it doesn't provide one vitally important piece of data: the list of databases on that server. To get that, we need to use more traditional database access methods.

But, to do that, we are going to have to connect to the server, which means a connection string, which means a username & password. SqlServerInfo provides read/write properties for those as well as a boolean IntegratedSecurity option (the other properties are read-only).

Once we've established a connection, getting the list of catalogs is a method built right into the OleDbConnection object:

C#
DataTable schemaTable = 
   myConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Catalogs, null);

Using the code

Everything is packaged in the class SqlServerInfo. It has one static method, Seek(), which gets the information about the SQL Server instances on the network, and returns an array of SqlServerInfo objects.

C#
SqlServerInfo[] servers = SqlServerInfo.Seek();

Each SqlServerInfo object contains a number of properties describing that particular MS SQL Server instance. Each of these is a read-only property.

  • public string ServerName
  • public string InstanceName
  • public bool IsClustered
  • public string Version
  • public int TcpPort
  • public string NamedPipe
  • public IPAddress Address

InstanceName is typically "MSSQLSERVER", which is the default if it isn't given a specific name at installation. Version should be "8.0.xxx" for SQL Server 2000. And TcpPort will typically be 1433.

Note that, although Address is a property, in the current implementation it will always be null --- until I can figure a way of finding out what the server's IP address is. The Socket.Receive method doesn't say what machine is sending the data -- it is just assumed to be the machine you just transmitted to -- the naiveté of which is apparent when one sends a broadcast message. (If anyone knows how to get that information out of a Socket, please let me know.)

Next there are four Read/Write properties, which must be set to get any more information out of this class:

  • public string UserId
  • public string Password
  • public bool IntegratedSecurity
  • public int TimeOut

These establish how we are going to attempt to connect to that server. IntegratedSecurity defaults to true, and TimeOut defaults to 2 seconds, so if these work for you, you don't have to do anything more. Setting either UserId or Password sets IntegratedSecurity to false.

The final property retrieves a list of databases available on the server.

  • public StringCollection Catalogs

The first time it is called, it will attempt to connect to the server, so the above property needs to be set right.

Finally, there are two methods:

  • public bool TestConnection()
  • public override string ToString()

TestConnection is just as its name says --- it tests if you can connect with the given userID/password.

ToString returns either the ServerName (if the InstanceName is the default) or ServerName / InstanceName. Either way it is what you need to specify as the Data Source in a connection string. As a ToString, you can set the DataSource property of a ListBox or similar control to an array of SqlServerInfo objects, and the appropriate values will be displayed.

C#
SqlServerInfo Data = servers[0];
Console.WriteLine(Data.ToString());
Console.WriteLine("Version:", Data.Version);

Data.IntegratedSecurity = true;
foreach(string Catalog in Data.Catalogs)
{
    Console.WriteLine("    {0}", Catalog);
}

History

  • 20-Nov 2005 - v 1.0 Initial release.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) NovelTheory LLC
United States United States
20+ years as a developer : Assembly, C, C++ and C# (in that order) with sidelines in ASP/VBScript, ASP.Net, JavaScript, Perl, QuickBasic, VisualBasic, plus a few others which I'm not going to mention because if I did someone might ask me to use them again (shudder)

Microsoft MVP in VC++ (1994-2004)

I also run www.NJTheater.com as a hobby.

Full resume & stuff at NovelTheory.com

Underused blog at HonestIllusion.com

Comments and Discussions

 
QuestionThanks Pin
gooriy22-Oct-14 3:35
gooriy22-Oct-14 3:35 
GeneralMy vote of 5 Pin
Akshay Srinivasan21-Feb-13 0:28
Akshay Srinivasan21-Feb-13 0:28 
GeneralMy vote of 5 Pin
Francis Judge9-Dec-11 1:39
Francis Judge9-Dec-11 1:39 
GeneralGreat! Pin
surecan18-Jul-11 10:41
surecan18-Jul-11 10:41 
GeneralHow to use? Pin
toeknee1010-May-11 6:07
toeknee1010-May-11 6:07 
GeneralDont understand ping to instances Pin
juliotrujilloleon12-Jan-10 7:30
juliotrujilloleon12-Jan-10 7:30 
QuestionSome nicely written code... but why all the extra work? Pin
Drew Stegon18-Dec-09 8:51
Drew Stegon18-Dec-09 8:51 
AnswerRe: Some nicely written code... but why all the extra work? Pin
Jeff Bowman30-Jan-23 14:42
professionalJeff Bowman30-Jan-23 14:42 

why all the extra work?


Because GetDataSources() takes a long time to complete, and it doesn't find all instances.

James' code runs instantly and finds all instances from all machines on the LAN.
GeneralGreat Pin
dexter_wrocek16-Oct-09 1:51
dexter_wrocek16-Oct-09 1:51 
GeneralSqlDataSourceEnumerator Pin
Motz31-Jul-09 8:34
Motz31-Jul-09 8:34 
QuestionDoes not show localhost Pin
Lord of Scripts9-Jul-09 21:05
Lord of Scripts9-Jul-09 21:05 
AnswerRe: Does not show localhost Pin
MyBestTools7-Oct-09 3:37
MyBestTools7-Oct-09 3:37 
GeneralSMO Short comming Pin
asmsoftware31-May-09 2:33
asmsoftware31-May-09 2:33 
GeneralSqlDataSourceEnumerator.Instance.GetDataSources() Pin
Jeremy Long9-Mar-09 13:36
Jeremy Long9-Mar-09 13:36 
GeneralRe: SqlDataSourceEnumerator.Instance.GetDataSources() Pin
Jeff Bowman30-Jan-23 14:43
professionalJeff Bowman30-Jan-23 14:43 
GeneralIP Address fix Pin
Salvador S. Delvisco Jr.19-Sep-08 10:34
Salvador S. Delvisco Jr.19-Sep-08 10:34 
GeneralGreat work James I made slight modifications for my purposes that i think might be useful for some. Pin
Member 105382019-Aug-08 5:35
Member 105382019-Aug-08 5:35 
GeneralUse SMO to get SQL Servers Pin
Member 476816314-May-08 22:13
Member 476816314-May-08 22:13 
AnswerRe: Use SMO to get SQL Servers Pin
Member 105382019-Aug-08 5:50
Member 105382019-Aug-08 5:50 
GeneralGot an Exception while comming in the loop second time Pin
nsadhasivam5-May-08 3:05
nsadhasivam5-May-08 3:05 
GeneralAlways times out, no servers respond Pin
ghawkes23-Mar-08 9:25
ghawkes23-Mar-08 9:25 
GeneralRe: Always times out, no servers respond Pin
nsadhasivam5-May-08 3:46
nsadhasivam5-May-08 3:46 
GeneralRe: Always times out, no servers respond Pin
Nat181018-Feb-09 22:32
Nat181018-Feb-09 22:32 
GeneralDoesn't return if the network is disabled Pin
arupk_das_200212-Nov-07 17:28
arupk_das_200212-Nov-07 17:28 
GeneralGet list of all the terminals Pin
Mathur Preeti9-Feb-07 19:21
Mathur Preeti9-Feb-07 19:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.