Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#
Article

Finding SQL Servers on the Network

Rate me:
Please Sign up or sign in to vote.
4.79/5 (83 votes)
22 Dec 2003Public Domain4 min read 326.3K   14.3K   126   74
Locating MS SQL Servers by using ODBC through C# PInvoke calls.

Sample Image - DBGrep.jpg

Introduction

I am a TSQL fanatic. The programs I code are highly dependent upon MS SQL stored procedures. I pay for this love of TSQL when a major overhaul of the system is necessary. Sometimes my code needs to be updated heavily in two places; client and server. To facilitate these updates, I created a database searching program I call DB Grep. It uses Regex to search out every reference to words or phrases in an entire database. The program has saved many hours of research and gives me the warm fuzzy "I didn’t miss anything" feeling.

When developing DB Grep, I ran into an interesting problem. How do I find the SQL Servers on my network?

Options

After many hours of web research, I came up with the following alternatives:

OptionProCon
No Location Services.No code to write.Typing in SQL server names by memory is a pain.
Use Windows OS Services.Using NetServerEnum is very fast.Does not always return the desired results. It returns Windows server names, not SQL Server names, and they are not always the same. It also does not work well on a non-domain based network. Couldn't find my local MSDE server.
Use the SQLDMO objects.Returns the desired results.Installation headaches. Installing COM objects is always problematic, not to mention possible license issues.
Use ODBCReturns the desired results. Should already be installed.Haven't found any yet.

Needless to say, I picked the ODBC solution. This required a bit of research with a lot of PInvoke trial and error.

I should state up front that this has not been tested on Windows 95/98/ME. I have decided that these operating systems are no longer necessary for my new development. The code has been tested on Windows 2000 and XP using Framework 1.1.

The Process

In order to acquire the names of the available SQL servers from ODBC, we have to allocate an environment, set the ODBC style and connect to the ODBC service. SQLAllocHandle() is used to get the environment and connection handles. In between the calls, it is necessary to specify what version of ODBC is to be used, by calling SQLSetEnvAttr(). I choose ODBC 3.0 using a system constant. Of course, you must always play nice with the ODBC resources by releasing both the environment and connection handles with matching calls to SQLFreeHandle().

I wrapped the allocation calls in a try block and the free calls in the finally section to ensure the release of the ODBC resources. The necessary PInvoke declarations to setup and tear down the ODBC environment are as follows:

C#
private const short SQL_HANDLE_ENV = 1;
private const short SQL_HANDLE_DBC = 2;
private const int SQL_ATTR_ODBC_VERSION = 200;
private const int SQL_OV_ODBC3 = 3;
private const short SQL_SUCCESS = 0;


[DllImport("odbc32.dll")]
private static extern short SQLAllocHandle(
    short hType, 
    IntPtr inputHandle, 
    out IntPtr outputHandle);
[DllImport("odbc32.dll")]
private static extern short SQLSetEnvAttr(
    IntPtr henv, 
    int attribute, 
    IntPtr valuePtr, 
    int strLength);
[DllImport("odbc32.dll")]
private static extern short SQLFreeHandle(
    short hType, 
    IntPtr handle);

Once the connection has been established, we can use a trick of the SQL ODBC driver to locate the advertising MS SQL servers. I attempt to open a MS SQL database connection using SQLBrowseConnect() by specifying only the SQL driver. The driver accommodates my request by building a connection string with the required parameters filled in with the possible values it can derive (like the available MS SQL Servers). It then returns a value stating that it needs more information. The server names can be easily parsed out of this connection string.

For speed, I pre-allocate a StringBuilder with a capacity of 1024 characters. In case of an extra large list of available servers, I test an out parameter to see if a larger string is necessary. I recall the SQLBrowseConnect() function with the newly resized string if necessary. The PInvoke for SQLBrowseConnect() call follows:

C#
private const short SQL_NEED_DATA = 99;
private const string SQL_DRIVER_STR = "DRIVER=SQL SERVER";
 
[DllImport("odbc32.dll",CharSet=CharSet.Ansi)]
private static extern short SQLBrowseConnect(
    IntPtr hconn, 
    StringBuilder inString, 
    short inStringLength, 
    StringBuilder outString, 
    short outStringLength, 
    out short outLengthNeeded);

For example, I pass "DRIVER=SQL SERVER" into SQLBrowseConnect() and get something like "SERVER:Server={(local),SQL_SERVER1,SQL_BKSVR};UID:Login ID=?; PWD:Password=?; *APP:AppName=?; *WSID:WorkStation ID=?" returned. It is a simplistic task to pull out the comma delimited substring between the two curly braces. To simplify the use of the server list, I call the Split() method on the substring to return a string array that can be used in a foreach statement.

For reuse, I encapsulated the PInvoke declarations and the static method within a class. Since this is just a helper method, I took precautions to hide any failures from release code and return a null string[] value in that case. A null return value indicates that no servers were found. Here is an example of calling the resultant code:

C#
string[] theAvailableSqlServers = SqlLocator.GetServers();
if (theAvailableSqlServers != null)
{
    myListBox.DataSource = theAvailableSqlServers;
} 
else
{
    MessageBox.Show("No SQL servers found.");
}

Summary

This code is more research than skill derived. Hopefully, I am able to save you a few hours of trudging through MSDN on a future project. If you do a lot of MS SQL work, you may be interested in my DB Grep program, which is freely available (with source) on GotDotNet. It currently works very well in my environment but, I am sure it could use a good workout elsewhere.

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication


Written By
Chief Technology Officer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: Correction Pin
Michael Potter24-Feb-05 3:35
Michael Potter24-Feb-05 3:35 
GeneralGreat Help - Note on multiple instances Pin
John Albright1-Jan-05 14:34
John Albright1-Jan-05 14:34 
GeneralRe: Great Help - Note on multiple instances Pin
John Albright2-Jan-05 5:26
John Albright2-Jan-05 5:26 
QuestionCan not find the local MSDE whit XP Prof SP2 an active firewall Pin
Member 151115714-Dec-04 3:08
Member 151115714-Dec-04 3:08 
AnswerRe: Can not find the local MSDE whit XP Prof SP2 an active firewall Pin
15-Dec-04 4:41
suss15-Dec-04 4:41 
GeneralDataTable question.. Pin
Besinci26-Sep-04 4:50
Besinci26-Sep-04 4:50 
QuestionHow to run Pin
MattFritzOO79-Sep-04 7:53
MattFritzOO79-Sep-04 7:53 
GeneralBrilliant Pin
CodeGimp19-Aug-04 0:27
CodeGimp19-Aug-04 0:27 
...absolutely bloody brilliant! EXACTLY what I needed; you've saved me ages. Thanks, and FANTASTIC work fella!

Smile | :)
GeneralRe: Brilliant Pin
Michael Potter21-Aug-04 5:28
Michael Potter21-Aug-04 5:28 
GeneralRe: Brilliant Pin
Alexander Ruscle25-Jan-05 8:07
Alexander Ruscle25-Jan-05 8:07 
GeneralRe: Brilliant Pin
RK KL1-Aug-05 20:10
RK KL1-Aug-05 20:10 
GeneralRe: Brilliant Pin
SinbaQL27-Dec-05 14:28
SinbaQL27-Dec-05 14:28 
Generalisql Pin
Small Rat29-Jul-04 17:00
Small Rat29-Jul-04 17:00 
GeneralRe: isql Pin
Anonymous30-Jul-04 15:43
Anonymous30-Jul-04 15:43 
GeneralGreate but work only if a network is present Pin
User 8748468-Jun-04 22:27
User 8748468-Jun-04 22:27 
GeneralRe: Greate but work only if a network is present Pin
Michael Potter9-Jun-04 3:08
Michael Potter9-Jun-04 3:08 
GeneralRe: Greate but work only if a network is present Pin
Jorge Da Silva8-Jul-04 5:16
Jorge Da Silva8-Jul-04 5:16 
GeneralRe: Greate but work only if a network is present Pin
Stefan Wey17-Sep-04 4:11
Stefan Wey17-Sep-04 4:11 
GeneralRe: Greate but work only if a network is present Pin
sunil.harris22-Nov-04 6:32
sunil.harris22-Nov-04 6:32 
GeneralServer Databases List Pin
nlaham11-May-04 12:07
nlaham11-May-04 12:07 
GeneralRe: Server Databases List Pin
Michael Potter11-May-04 17:28
Michael Potter11-May-04 17:28 
GeneralRe: Server Databases List Pin
nlaham12-May-04 5:08
nlaham12-May-04 5:08 
GeneralRe: Server Databases List Pin
Michael Potter12-May-04 5:33
Michael Potter12-May-04 5:33 
GeneralRe: Server Databases List Pin
nlaham14-May-04 9:36
nlaham14-May-04 9:36 
GeneralRe: Server Databases List Pin
Anonymous15-Nov-04 2:58
Anonymous15-Nov-04 2:58 

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.