Solved

code snippet gets network info - pass params?

Posted on 2012-03-15
8
394 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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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
Comment Utility
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
Comment Utility
0
 
LVL 5

Author Comment

by:knowlton
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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
Comment Utility
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 74

Accepted Solution

by:
käµfm³d   👽 earned 400 total points
Comment Utility
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
Comment Utility
Thank you!
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
This video discusses moving either the default database or any database to a new volume.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

771 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

10 Experts available now in Live!

Get 1:1 Help Now