# Retrieving SqlServer Instances using C#



## Kreij (Jun 2, 2009)

I am writing a networking application that needed to find all of the SqlServer instances on my local lan and put them in a ComboBox. So I dug into it and created the following ...

```
int count = 0;
string receiveInfo;
string[] Info;
string ServerName = String.Empty, InstanceName = String.Empty;

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.EnableBroadcast = true;
socket.ReceiveTimeout = 3000;
IPEndPoint ipep = new IPEndPoint(IPAddress.Broadcast, 1434);

try
{
    byte[] msg = new byte[] { 0x02 };
    socket.SendTo(msg, ipep);
    byte[] byteBuffer = new byte[1024];
    do
    {
        count = socket.Receive(byteBuffer);
        receiveInfo = ASCIIEncoding.ASCII.GetString(byteBuffer, 3, BitConverter.ToInt16(byteBuffer, 1));
        Info = receiveInfo.Split(';');
        for (int i = 0; i < Info.Length; i += 2)
        {
            switch (Info[i])
            {
                case "ServerName":
                    ServerName = Info[i + 1];
                    break;
                case "InstanceName":
                    InstanceName = Info[i + 1];
                    break;
            }
        }
        instanceCombobox.Items.Add(ServerName + "\\" + InstanceName);

    } while (count != 0);
}
catch (SocketException SExc)
    {
        const int WSAETIMEDOUT = 10060;
        const int WSAEHOSTUNREACH = 10065;
        if (SExc.ErrorCode == WSAETIMEDOUT || SExc.ErrorCode == WSAEHOSTUNREACH)
        {
            // Do Nothing
        }
        else
        {
            throw;
        }
    }
finally
{
    socket.Close();
}
```

It works really well. Then I discovered that the .Net Framework has a built in Sql DataSource enumerator that does the exact same thing in 4 lines of code.

```
SqlDataSourceEnumerator sdse = SqlDataSourceEnumerator.Instance;
DataTable table = sdse.GetDataSources();
foreach (DataRow row in table.Rows)
{
    instanceCombobox.Items.Add(row["ServerName"].ToString() + "\\" + row["InstanceName"].ToString());
}
```

 

Hope this helps someone.


----------



## Disparia (Jun 3, 2009)

LOL, I would have though to check for that stuff first, and I'm not much of an application programmer. 

Just ribbin' ya a little.

Thanks!


----------

