Solved

code snippet gets network info - pass params?

Posted on 2012-03-15
8
413 Views
Last Modified: 2012-03-15
I found this snippet for getting netstat type info inside of a C# console application:

private static void GetNetStatInfo()
        {
            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();

            IPEndPoint[] endPoints = ipProperties.GetActiveTcpListeners();
            TcpConnectionInformation[] tcpConnections = ipProperties.GetActiveTcpConnections();

            foreach (TcpConnectionInformation info in tcpConnections)
            {
                Console.WriteLine("Local : " + info.LocalEndPoint.Address.ToString()
                + ":" + info.LocalEndPoint.Port.ToString()
                + "\nRemote : " + info.RemoteEndPoint.Address.ToString()
                + ":" + info.RemoteEndPoint.Port.ToString()
                + "\nState : " + info.State.ToString() + "\n\n");
            }
            Console.ReadLine();
        }

Open in new window



Is this using netstat to get the information?

What I want is to get the same info that the following command line call would obtain:

netstat -nbo

Please provide code, either modify my code or provide alternative code to do this.
0
Comment
Question by:knowlton
  • 4
  • 3
8 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37725723
That's closer to a netstat -n, but without the protocol information. A netstat -bno could be possible in C#, but before we delve into that, could executing netstat -bno from within your application and parsing the STDOUT of that process be an option?
0
 
LVL 5

Author Comment

by:knowlton
ID: 37725762
It could be an option, sure.

All I am really wanting is to get a list of the socket connections opened on the server that are opened because of my call to a webservice method.

I want to monitor the state of the socket connections (ESTABLISHED, TIME_WAIT, CLOSE_WAIT, etc.) so I can determine how long they are staying open after the webservice method is done with it's work   and / or   the calling application has closed.

I just want to dump the netstat results into a ListBox or something.
0
 
LVL 20

Assisted Solution

by:BuggyCoder
BuggyCoder earned 100 total points
ID: 37725764
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 5

Author Comment

by:knowlton
ID: 37725790
have a look at this:-
http://stackoverflow.com/questions/577433/which-pid-listens-on-a-given-port-in-c-sharp

and this as well:-

http://stackoverflow.com/questions/2775648/netstat-ban-or-oan-equivalent-in-net


Going to wait for some other options.  Surely there is a more ".NET" way to do this?
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37725870
Going to wait for some other options.  Surely there is a more ".NET" way to do this?
This is the reason I asked about parsing netstat -bno: I have a feeling doing with direct queries to the system will involve using the Win API and P/Invoke.
0
 
LVL 5

Author Comment

by:knowlton
ID: 37725991
This is the reason I asked about parsing netstat -bno: I have a feeling doing with direct queries to the system will involve using the Win API and P/Invoke.

Open in new window


Let's explore parsing netstat -bno as you suggest.
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 400 total points
ID: 37726037
In lieu of getting a neat class which does all of this, you might try the following. I've only mildly tested it, so it may require some tweaking, but it should be pretty straigh-forward. It simply parses the result of a call to netstat -bno.

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace _27633978
{
    class Program
    {
        static void Main(string[] args)
        {
            List<PortInfo> netstatInfo = GetParsedNetstat();

            foreach (var nsInfo in netstatInfo)
            {
                Console.WriteLine("Protocol: {0}", nsInfo.Protocol);
                Console.WriteLine("Local Address: {0}", nsInfo.LocalAddress);
                Console.WriteLine("Local Port: {0}", nsInfo.LocalPort);
                Console.WriteLine("Foreign Address: {0}", nsInfo.ForeignAddress);
                Console.WriteLine("Foreign Port: {0}", nsInfo.ForeignPort);
                Console.WriteLine("State: {0}", nsInfo.State);
                Console.WriteLine("PID: {0}", nsInfo.PID);
                Console.WriteLine("Process Name: {0}", nsInfo.ProcName);
                Console.WriteLine();
            }

            Console.ReadKey();
        }

        private static List<PortInfo> GetParsedNetstat()
        {
            List<PortInfo> result = new List<PortInfo>();
            ProcessStartInfo info = new ProcessStartInfo()
            {
                FileName = "netstat",
                Arguments = "-bno",
                RedirectStandardOutput = true,
                UseShellExecute = false,
            };

            using (Process p = Process.Start(info))
            {
                p.StandardOutput.ReadLine();    // Skip blank line
                p.StandardOutput.ReadLine();    // Skip "Active Connections"
                p.StandardOutput.ReadLine();    // Skip blank line
                p.StandardOutput.ReadLine();    // Skip column headers

                while (!p.StandardOutput.EndOfStream)
                {
                    PortInfo pi = new PortInfo();
                    string connectionDetails = p.StandardOutput.ReadLine();

                    GetValues(pi, connectionDetails);

                    pi.ProcName = (p.StandardOutput.ReadLine() ?? string.Empty).Trim();
                    pi.ProcName = pi.ProcName.Substring(1, pi.ProcName.Length - 2); // Remove brackets

                    result.Add(pi);

                    p.StandardOutput.ReadLine();    // Skip blank line
                }
            }

            return result;
        }

        private static void GetValues(PortInfo pi, string detailLine)
        {
            int idx = 0;
            int start;

            for (; char.IsWhiteSpace(detailLine[idx]); idx++) ; // Skip leading whitespace

            start = idx;

            for (; !char.IsWhiteSpace(detailLine[idx]); idx++) ; // Locate end of first field

            pi.Protocol = detailLine.Substring(start, idx - start);

            for (; char.IsWhiteSpace(detailLine[idx]); idx++) ; // Skip whitespace

            start = idx;

            for (; detailLine[idx] != ':'; idx++) ; // Locate end of local IP address

            pi.LocalAddress = detailLine.Substring(start, idx - start);

            start = idx + 1;

            for (; !char.IsWhiteSpace(detailLine[idx]); idx++) ; // Locate end of local port number

            pi.LocalPort = detailLine.Substring(start, idx - start);

            for (; char.IsWhiteSpace(detailLine[idx]); idx++) ; // Skip whitespace

            start = idx;

            for (; detailLine[idx] != ':'; idx++) ; // Locate end of foreign IP address

            pi.ForeignAddress = detailLine.Substring(start, idx - start);

            start = idx + 1;

            for (; !char.IsWhiteSpace(detailLine[idx]); idx++) ; // Locate end of foreign port number

            pi.ForeignPort = detailLine.Substring(start, idx - start);

            for (; char.IsWhiteSpace(detailLine[idx]); idx++) ; // Skip whitespace

            start = idx;

            for (; !char.IsWhiteSpace(detailLine[idx]); idx++) ; // Locate end of state field

            pi.State = detailLine.Substring(start, idx - start);

            for (; char.IsWhiteSpace(detailLine[idx]); idx++) ; // Skip whitespace

            start = idx;

            pi.PID = detailLine.Substring(start, detailLine.Length - start);
        }
    }

    public class PortInfo
    {
        public string Protocol { get; set; }
        public string LocalAddress { get; set; }
        public string LocalPort { get; set; }
        public string ForeignAddress { get; set; }
        public string ForeignPort { get; set; }
        public string State { get; set; }
        public string PID { get; set; }
        public string ProcName { get; set; }
    }
}

Open in new window

0
 
LVL 5

Author Closing Comment

by:knowlton
ID: 37726427
Thank you!
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

816 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now