Reputation: 249
I use C# driver for MongoDB. Can I get the list of all MonogDB servers in my local network like with SqlDataSourceEnumerator for MS SQL servers?
Thank you.
Upvotes: 1
Views: 185
Reputation: 59793
No, there is not a built in way to discover all MongoDB servers within a network. While I see there is an answer proposed for essentially port-scanning, this is flawed on many levels.
SqlDataSourceEnumerator
class works by sending a broadcast packet to the local network segment. It's extremely efficient as "all" devices on that segment will receive the packet and have the option of responding. I normally would recommend just storing centrally a list of active MongoDB servers.
Upvotes: 1
Reputation: 21649
What you can do is a find all the active IPv4 addresses. You can find how to do it here (answered by Ken Fyrstenberg)
Then use HttpClient object to get the response form all IPs you found but on the port 27017 try { // Create a New HttpClient object. HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://localhost:27017/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method in following line
// string body = await client.GetStringAsync(uri);
Console.WriteLine(responseBody); //HERE you can check for "MongoDB"
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
Response will be as follows(Mongod instance is running on specific ip):
You are trying to access MongoDB on the native driver port. For http diagnostic access, add 1000 to the port number
So, by using response string you can figure out whether a Mongod instance is running on specific ip or not.
This may not work if the MongoDB port is customized (other than default:27017). For more information on MongoDB's Network Exposure and Security
Upvotes: 2