Last active
October 18, 2016 12:23
-
-
Save kosmakoff/7449760 to your computer and use it in GitHub Desktop.
Enumerating MS SQL Server instances in different ways
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Data; | |
using System.Linq; | |
using System.Net; | |
using System.Net.Sockets; | |
using System.Text; | |
using System.Text.RegularExpressions; | |
using Microsoft.SqlServer.Management.Smo; | |
namespace EnumSqlServers | |
{ | |
internal class Program | |
{ | |
private static void Main() | |
{ | |
try | |
{ | |
// 1. Try library method | |
var dataTable = SmoApplication.EnumAvailableSqlServers(false); | |
if (dataTable.Rows.Count > 0) | |
{ | |
foreach (DataRow row in dataTable.Rows) | |
{ | |
Console.WriteLine("{0}", row["Name"]); | |
} | |
} | |
// 2. Using sockets | |
var socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp) | |
{ | |
EnableBroadcast = true, | |
ReceiveTimeout = 1000, | |
DualMode = true | |
}; | |
var bytes = new List<byte>(4096); | |
try | |
{ | |
var ipv4ep = new IPEndPoint(IPAddress.Broadcast, 1434); | |
var ipv6ep = new IPEndPoint(IPAddress.Parse("ff02::1"), 1434); | |
byte[] msg = {0x02}; | |
socket.SendTo(msg, ipv4ep); | |
socket.SendTo(msg, ipv6ep); | |
int cnt = 0; | |
byte[] byteBuffer = new byte[256]; | |
do | |
{ | |
cnt = socket.Receive(byteBuffer); | |
bytes.AddRange(byteBuffer.Take(cnt)); | |
} while (cnt != 0); | |
} | |
catch (SocketException sex) | |
{ | |
const int WSAETIMEDOUT = 10060; // Connection timed out. | |
const int WSAEHOSTUNREACH = 10065; // No route to host. | |
if (sex.ErrorCode == WSAETIMEDOUT || sex.ErrorCode == WSAEHOSTUNREACH) | |
{ | |
} | |
else | |
{ | |
throw; | |
} | |
} | |
finally | |
{ | |
socket.Close(); | |
} | |
string text = Encoding.ASCII.GetString(bytes.ToArray()); | |
var servers = text.Split(new[] {";;"}, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Substring(s.IndexOf("ServerName", StringComparison.Ordinal))); | |
var regex = new Regex(@"^ServerName;(?<server>\w+);InstanceName;(?<instance>\w+);.*", RegexOptions.Compiled); | |
Console.WriteLine(); | |
foreach (var server in servers) | |
{ | |
// parse it with regex | |
var match = regex.Match(server); | |
Console.WriteLine("{0}\\{1}", match.Groups["server"], match.Groups["instance"]); | |
} | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.Message); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment