Wednesday, April 25, 2012

C# and PowerShell EHLO Response

Earlier today, one of my colleagues put down a challenge to create in .NET and PowerShell a way detect if a remote email server was running Exchange via a EHLO response. Below are the code examples that completed the task.


C# (Console Application)
//Var for TCP Port
Int32 port = 25;
//Byte Array for Response Data
Byte[] rData = new Byte[256];
//Var for Converted Response Data
string responseData = string.Empty;
//Create a TcpClient
TcpClient client = new TcpClient("smtp.dept.mycollege.edu", port);
//Byte Array for Message to Be Sent
Byte[] data = System.Text.Encoding.ASCII.GetBytes("EHLO");
//Initate a Stream
NetworkStream stream = client.GetStream();
//Send Message to Server
stream.Write(data, 0, data.Length);
//Initiate Int for Return Bytes and Read Response of Stream
Int32 bytes = stream.Read(rData, 0, rData.Length);
//Convert Response
responseData = System.Text.Encoding.ASCII.GetString(rData, 0, bytes);
//Write Out Response 
Console.WriteLine(responseData);
//Close Stream and Client
stream.Close();
client.Close();


PowerShell
#Var for TCP Port
[int]$port = 25;
#Byte Array for Response Data
$rData = New-Object Byte[](256);
#Var for Converted Response Data
$responseData = "";
#Create a TcpClient
$tClient = New-Object System.Net.Sockets.TcpClient("smtp.dept.mycollege.edu",$port);
#ASCII Encoder
$encode = [System.Text.Encoding]::ASCII
#Byte Array for Message to Be Sent
[Byte[]]$sData = $encode.GetBytes("EHLO");
#Initiate a Stream
$stream = $tClient.GetStream();
#Send Message to Server
$stream.Write($sData,0,$sData.Length);
#Initiate Int for Return Bytes and Read Response of Stream
[int]$bytes = $stream.Read($rData,0,$rData.Length);
#Convert Response
$responseData = $encode.GetString($rData,0,$bytes);
#Notify User 
Write-Host $responseData;
#Close Stream and Client
$stream.Close();
$tClient.Close();