Artem Tsetkhalin
Artem Tsetkhalin

Reputation: 249

MongoDB. The list of all servers

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

Answers (2)

WiredPrairie
WiredPrairie

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.

  1. The 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.
  2. The port for MongoDB may have been changed from the default (and MongoDB config servers run on a different port by default). I usually don't use the default port to make sure it's not hardcoded somewhere. :)
  3. Without knowledge of the various segments of your LAN, you may not know where to actually scan (like what ranges of IP addresses?)
  4. It may be configured with SSL
  5. You may trigger security alerts within an enterprise for doing a port scan
  6. Firewalls may block the traffic from unauthorized hosts (and in a typical enterprise, this would be the case)
  7. I wouldn't make long term use of IPV4 as enterprises move to IPV6

I normally would recommend just storing centrally a list of active MongoDB servers.

Upvotes: 1

Amol M Kulkarni
Amol M Kulkarni

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

Related Questions