Solved

code snippet gets network info - pass params?

Posted on 2012-03-15
8
425 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:Tom Knowlton
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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:Tom 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
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
LVL 5

Author Comment

by:Tom 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:Tom 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:Tom Knowlton
ID: 37726427
Thank you!
0

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

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…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

740 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