5,426,531 members and growing! (14,811 online)
Email Password   helpLost your password?
Database » Database » SQL Server     Intermediate

Finding SQL Servers on the Network

By Michael Potter

Locating MS SQL Servers by using ODBC through C# PInvoke calls.
C#.NET 1.1, Win2K, WinXP, Win2003, Windows, .NET, Visual Studio, DBA, Dev

Posted: 22 Dec 2003
Updated: 22 Dec 2003
Views: 154,174
Bookmarked: 95 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
76 votes for this Article.
Popularity: 8.31 Rating: 4.42 out of 5
3 votes, 3.9%
1
1 vote, 1.3%
2
2 votes, 2.6%
3
9 votes, 11.8%
4
61 votes, 80.3%
5

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:

Option Pro Con
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 ODBC Returns 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:

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:

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:

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Michael Potter



Occupation: Web Developer
Location: United States United States

Other popular Database articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 70 (Total in Forum: 70) (Refresh)FirstPrevNext
Subject  Author Date 
QuestionLicensememberSparkley Doodads8:37 14 Jul '08  
AnswerRe: LicensememberMichael Potter8:59 14 Jul '08  
GeneralVery BadmemberDevelopmentTech5:49 6 Jul '08  
GeneralThanksmemberGeethanga Amarasinghe19:19 9 Oct '07  
Questionconnect to database in sql?memberlildiapaz5:11 5 Jul '07  
Generalusing your GetSqlClassmemberRepliCrux16:12 19 Jun '07  
GeneralUse with Sybase 9memberChris_McGrath16:06 6 Apr '06  
QuestionCannot see local sql server (MSDE) when .NET Framework 2.0 is installedmemberCaJuDo1:03 23 Jan '06  
AnswerRe: Cannot see local sql server (MSDE) when .NET Framework 2.0 is installedmemberTommi G16:13 25 Oct '06  
GeneralApp Failed to Initializememberdna19907:28 12 Jan '06  
GeneralRe: App Failed to InitializememberMichael Potter9:04 12 Jan '06  
GeneralHelp me,please.memberSinbaQL18:07 29 Dec '05  
GeneralHow get the Infomation about the stored procedures and so on.memberSinbaQL15:45 29 Dec '05  
GeneralNew link for DB GrepsupporterEnrico Detoma0:29 27 Dec '05  
GeneralRe: New link for DB GrepmemberSinbaQL23:05 27 Dec '05  
GeneralNew Class supportmemberwschlichtman15:00 10 Sep '05  
GeneralNice work!memberkris.mackintosh13:43 14 Jul '05  
Generalmanipulating server?memberUnruled Boy18:41 19 Jun '05  
GeneralI need to help: how to get sever name, database name to update connection string?memberheovissan18:23 2 Jun '05  
GeneralRe: I need to help: how to get sever name, database name to update connection string?memberSinbaQL3:54 28 Dec '05  
GeneralProblem ...please helpmemberpubududilena17:56 8 May '05  
GeneralRe: Problem ...please helpmemberMichael Potter3:43 9 May '05  
GeneralCorrectionmemberDavid M. Kean18:41 23 Feb '05  
GeneralRe: CorrectionmemberDavid M. Kean19:24 23 Feb '05  
GeneralRe: CorrectionmemberMichael Potter4:35 24 Feb '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 22 Dec 2003
Editor: Smitha Vijayan
Copyright 2003 by Michael Potter
Everything else Copyright © CodeProject, 1999-2008
Web16 | Advertise on the Code Project