C # 3.0: find SMTP servers in a domain
I doubt the domain servers are explicitly posting the fact that they are SMTP servers (I could be wrong), although the solution should be pretty straightforward nonetheless.
- Find every server in the active domain.
- An attempt was made to connect to a server on port 25 (SMTP).
- Wait for a response
220
that indicates the server is ready. (See the RFC for the protocol.) If you receive this command within a certain amount of time after connecting (say, 3 seconds), then you may conclude that the current computer is an SMTP server.
Hope it helps.
a source to share
I don't think you can do this with DirectoryServices.
One option is to try to connect to every server in the domain of the SMTP port (25) and see if they respond to standard SMTP commands. This can be easily done using the TcpClient class if you have a list of machines in the domain.
Of course, this will not result in the servers not using the standard port (but if the server is not using the standard port, it might not be of interest in the first place :-)
a source to share
Based on Noldorin's suggestion, here is some code, please note that I'm just connecting to 25, I'm not expecting 220 from the server. This worked on our domain. This is a brutal regex for getting server name based on LDAP path.
static void Main()
{
DirectorySearcher ds = new DirectorySearcher("");
ds.Filter = "objectCategory=computer";
SearchResultCollection results = ds.FindAll();
foreach (SearchResult result in results)
{
string pattern = @"(?<=LDAP://CN=)(?<serverName>\w*)(?=,*)";
Match m = Regex.Match(result.Path, pattern);
string serverName = m.Groups["serverName"].Value;
System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient();
try
{
tcp.Connect(serverName, 25);
if (tcp.Connected)
{
Console.WriteLine(String.Format("Connected to {0} on Port 25", serverName));
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
finally
{
tcp.Close();
}
}
Console.WriteLine("Done.");
Console.ReadLine();
}
Also, I think FindAll suffers from the usual AD limitation of 1000 results, so if you have more than 1000 servers in your domain you will have to rework
a source to share
If you want to find a domain mail server to send mail to that domain then using DNS MX is the way to go, as mjmarh already suggested. If you want to identify all arbitrary SMTP services in your domain using AD, you can take advantage of the fact that most SMTP servers register with AD, such as Exchange, and you can poll AD services to find out their location. For example, this white paper explains how Outlook clients discover their mailbox server using active directories: http://technet.microsoft.com/en-us/library/bb332063.aspx In a specific domain doing port scans on all machines. any intrusion detection mechanism they have like a Christmas tree will be highlighted and you can complete your application network address.
a source to share