Archive

Posts Tagged ‘NetStat’

Read remote computer Netstat value

December 28, 2010 1 comment

On MSDN get more information on NetStat tool, which is a tool that displays statistical information about network traffic. Depending on the arguments supplied at the command line, NetStatTool collects and displays information about network connections, listening ports, and packets sent and received by the local computer. The tool uses classes in the System.Net and System.Net.NetworkInformation namespaces to gather and display information about network protocols and current TCP/IP network connections.  However, MSDN sample shows how to get the information from the  local computer not the remote computer.

To get the remote computer NetStat values I have to fall back on PsExec. Here is a code to read remote computer NetStat values.

static void Main(string[] args)
{
 System.Diagnostics.Process proc = new System.Diagnostics.Process();
 proc.StartInfo.FileName = @"\\LocalComputer\temp\pstools\psexec.exe";
 proc.StartInfo.Arguments = @"\\RemoteComputer netstat -n -o -a -p tcp ";
//proc.StartInfo.Domain = "YourDomainName";
//proc.StartInfo.UserName = "UserName";
//string pwd = "Password";
//System.Security.SecureString secret = new System.Security.SecureString();
//foreach (char c in pwd)
// secret.AppendChar(c);
//proc.StartInfo.Password = secret;
 proc.StartInfo.UseShellExecute = false;
 proc.StartInfo.RedirectStandardOutput = true ;
 proc.Start();
 string s = proc.StandardOutput.ReadToEnd();
 /* Clean the string */
 s = s.Substring(s.IndexOf("Proto"), s.Length - s.IndexOf("Proto"));
 s = s.Replace("Local Address", "LocalAddress");
 s = s.Replace("Foreign Address", "ForeignAddress");
 s = s.Replace (@"\r\n"," ");
/* Get all the details */
 string[] values = s.Split( new string [] {" "}, StringSplitOptions.RemoveEmptyEntries);
 proc.Close();

}

Now if you want to find out how many connections were established from a given local address, you can change your code as follows:
System.Text.RegularExpressions.MatchCollection established = System.Text.RegularExpressions.Regex.Matches(s, @”:22731[0-9. :]+ESTABLISHED”);
var i = established.Count;

In my case I don’t have to use the userId and Password, but you may need it.

I am sure, you can do the same thing with WMI, which i will leave for next time.

Categories: C# Tags: , ,
Follow

Get every new post delivered to your Inbox.