Solved

code snippet gets network info - pass params?

Posted on 2012-03-15
8
407 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
 
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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
This code tracks birthdays 3 60
Error on Add method 1 38
C# HTTP GET method sample code 3 41
Error on link 14 38
A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
It seems a simple enough task, yet I see repeated questions asking how to do it: how to pass data between two forms. In this article, I will show you the different mechanisms available for you to do just that. This article is directed towards the .N…
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

896 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

14 Experts available now in Live!

Get 1:1 Help Now