Acessing netstat-like data with .NET

2020-04-23 02:41发布

I'd like to know if there is any way to access info like number of discarded packets from within .NET framework. I am aware of Win32_PerRawData and Ip Helper API. Thanks in advance

2条回答
等我变得足够好
2楼-- · 2020-04-23 03:21

This is lazy and cheating here but....I know I will get flamed for this...Would you not consider using a process to execute netstat -e n where n is the interval in number of seconds. If you are talking about a Winforms/WPF, using the System.Diagnostics.Process class to shell out to a hidden window with the output redirected to an input stream in which you can parse the discarded packets?

Edit: Here's a suggested code sample

    public class TestNetStat
    {
        private StringBuilder sbRedirectedOutput = new StringBuilder();
        public string OutputData
        {
            get { return this.sbRedirectedOutput.ToString(); }
        }
        public void Run()
        {
            System.Diagnostics.ProcessStartInfo ps = new System.Diagnostics.ProcessStartInfo();
            ps.FileName = "netstat";
            ps.ErrorDialog = false;
            ps.Arguments = "-e 30";   // Every 30 seconds
            ps.CreateNoWindow = true;
            ps.UseShellExecute = false;
            ps.RedirectStandardOutput = true;
            ps.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

            using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
            {
                proc.StartInfo = ps;
                proc.Exited += new EventHandler(proc_Exited);
                proc.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(proc_OutputDataReceived);
                proc.Start();
                proc.WaitForExit();
                proc.BeginOutputReadLine();
                while (!proc.HasExited) ;
            }
        }

        void proc_Exited(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("proc_Exited: Process Ended");
        }

        void proc_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
        {
            if (e.Data != null) this.sbRedirectedOutput.Append(e.Data + Environment.NewLine);
            // Start parsing the sbRedirected for Discarded packets...
        }
    }

Simple, hidden window....

Hope this helps, Best regards, Tom.

查看更多
放荡不羁爱自由
3楼-- · 2020-04-23 03:22

Your can use the PerformanceCounter class. Run Perfmon.exe to find out what's available on your machine. You should have Network Interface + Packets Received Discarded for each of your network adapters for example.

查看更多
登录 后发表回答