?
Solved

code snippet gets network info - pass params?

Posted on 2012-03-15
8
Medium Priority
?
445 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 400 total points
ID: 37725764
0
 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

 
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 1600 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

Want to be a Web Developer? Get Certified Today!

Enroll in the Certified Web Development Professional course package to learn HTML, Javascript, and PHP. Build a solid foundation to work toward your dream job!

Question has a verified solution.

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

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

777 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