Getting a list of SQL Server names in C++

hec6srdp  于 12个月前  发布在  SQL Server
关注(0)|答案(1)|浏览(124)

I know that with SQL Server Management Studio, you can choose "<Browse for more...>" and get a list of servers. I am looking at how to do this with C++. I would like to get a list that I can populate into a ComboBox. I don't define the database until after I get the SQL Server Name. The code I'm trying to enhance is written in C++ with MFC, so I'm stuck with that technology.

I've done a lot of searching, and many of the answers are not a programmatic solution. Those that are have been in C#. They have also been rather old.

zpf6vheq

zpf6vheq1#

SQL Server Management Studio uses the SQL Server Browser service to find instances of SQL Server.

The Browser service uses SQL Server Resolution Protocol, which is documented here:

https://learn.microsoft.com/en-us/openspecs/windows_protocols/MC-SQLR/1ea6e25f-bff9-4364-ba21-5dc449a601b7

The protocol is pretty simple--no security, no authentication, etc. To get a list of local servers, you basically just broadcast a one-byte packet containing the magic value '2' to UDP port 1434, and get back responses. Each response has a one-byte "magic" value to say that yes, this is a response, a length field, and then all the data in a semi-structured string. The documentation linked above gives details of the string, so I won't repeat it here. For that matter, a lot of it is pretty easy to figure out, even without any documentation (e.g., it starts with something like: "ServerName";Foo;"InstanceName";Bar , which, obviously enough, means an instance named Bar on a server named Foo ).

If you only care about instances on a single physical server, you can send a unicast packet (containing 3 instead of 2 ) to the specific address you care about. But most people want all servers...

相关问题