C # Implementation of Netstat functions

Source: Internet
Author: User
The core idea is to call the WINAPI

The Getextendedtcptable method to get information about all active TCP connections, including process IDs, is mainly implemented as follows:

TcpConnectionTableHelper.cs:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Runtime.InteropServices;
Using System.Text;

Using System.Threading.Tasks;
        Namespace Tcpconnectionmonitor {public class Tcpconnectiontablehelper {[DllImport ("Ws2_32.dll")]

        static extern ushort Ntohs (ushort netshort); [DllImport ("Iphlpapi.dll", SetLastError = True)] static extern uint Getextendedtcptable (IntPtr ptcptable, ref int

        Dwoutbuflen, bool sort, int ipversion, tcp_table_type tblclass, int reserved);
            [StructLayout (layoutkind.sequential)] public struct MIB_TCPROW_OWNER_PID {public uint State;
            public UINT LOCALADDR;
            public byte LocalPort1;
            public byte LocalPort2;
            public byte LocalPort3;
            public byte LocalPort4;
            public UINT remoteaddr;
            public byte RemotePort1;
            public byte RemotePort2;
          public byte RemotePort3;  public byte RemotePort4;

            public int owningpid; Public ushort LocalPort {get {return bitconverter.touint
                (New byte[2] {localPort2, localPort1}, 0);
                    } public ushort RemotePort {get {
                Return bitconverter.touint16 (new byte[2] {remotePort2, remotePort1}, 0);
        }} [StructLayout (layoutkind.sequential)] public struct MIB_TCPTABLE_OWNER_PID
            {public UINT dwnumentries;
        Mib_tcprow_owner_pid table; public static string getipaddress (long Ipaddrs) {try {System.
                net.ipaddress ipaddress = new System.Net.IPAddress (Ipaddrs);
            return ipaddress.tostring ();

        Catch {return ipaddrs.tostring ();}

       } public static ushort Gettcpport (int tcpport) {return Ntohs ((ushort) tcpport); public static mib_tcprow_owner_pid[] Getalltcpconnections () {mib_tcprow_owner_pid[] Tcpcon
            Nectionrows;    int af_inet = 2;

            IPv4 int buffsize = 0; Use WINAPI getextendedtcptable to query all active TCP connection information UINT RET = GETEXTENDEDTCPTABL E (IntPtr.Zero, ref buffsize, True, Af_inet, Tcp_table_type.
            Tcp_table_owner_pid_all, 0); if (Ret!= 0 && ret!= 122)//122 means insufficient buffer size {throw new exceptio
            N ("Error occurred when trying to query TCP table, return code:" + ret);

            } IntPtr bufftable = Marshal.allochglobal (buffsize); try {ret = getextendedtcptable (bufftable, ref buffsize, True, Af_inet, Tcp_table_type.
                Tcp_table_owner_pid_all, 0); if (ret!= 0) {throw new Exception ("Error occurred when trying to query TCP table, return cod
                E: "+ ret); }//Get the number of entries in the table mib_tcptable_owner_pid table = (mib_tcptable_
                Owner_pid) Marshal.PtrToStructure (Bufftable, typeof (Mib_tcptable_owner_pid));
                IntPtr rowptr = (INTPTR) ((long) bufftable + marshal.sizeof (table.dwnumentries));

                Tcpconnectionrows = new Mib_tcprow_owner_pid[table.dwnumentries]; for (int i = 0; i < table.dwnumentries i++) {mib_tcprow_owner_pid Tcprow = (mib_t
                    Cprow_owner_pid) Marshal.PtrToStructure (Rowptr, typeof (Mib_tcprow_owner_pid));
                    Tcpconnectionrows[i] = Tcprow;
                Rowptr = (INTPTR) ((long) rowptr + marshal.sizeof (tcprow)); } finally {//free memory Marshal.freehGlobal (bufftable);
        return tcpconnectionrows; }} public enum Tcp_table_type:int {tcp_table_basic_listener, tcp_table_basic_connections, tcp_table _basic_all, Tcp_table_owner_pid_listener, Tcp_table_owner_pid_connections, Tcp_table_owner_pid_all, TCP_TA Ble_owner_module_listener, Tcp_table_owner_module_connections, tcp_table_owner_module_all} public enum TCP_CONNE ction_state:int {CLOSED = 1, listening, syn_sent, SYN_RCVD, established, Fin_wait_1, Fin_wa It_2, Close_wait, CLOSING, Last_ack, time_wait, delete_tcp};


Program.cs:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading;

Using System.Threading.Tasks; Namespace Tcpconnectionmonitor {class Program {static void Main (string[] args) {Mon
        Itortcpconnections (); } static void Monitortcpconnections () {Console.WriteLine ("Proto Local address Fore
            IGN address State PID ");
            list<string> rows = new list<string> ();  while (true) {int windowtop = Console.windowtop; In order to keep console scroll bar stay tcpconnectiontablehelper.mib_tcprow_owner_pid[] Tcpprogressinfo
                Table = Tcpconnectiontablehelper.getalltcpconnections ();
                int tablerowcount = Tcpprogressinfotable.length; for (int i = 0; i < Tablerowcount i++) {Tcpconnectiontablehelper.mib_tcprow_owner _pid Row = Tcpprogressinfotable[i]; String Source = String. Format ("{0}:{1}", Tcpconnectiontablehelper.getipaddress (ROW.LOCALADDR), row.
                    LocalPort); String dest = String. Format ("{0}:{1}", Tcpconnectiontablehelper.getipaddress (ROW.REMOTEADDR), row.
                    RemotePort); String Outputrow = String.
                    Format ("{0, -7}{1, -23}{2, -23}{3, -16}{4}", "TCP", Source, Dest, (tcp_connection_state) row.state, row.owningpid); If rows.
                        Count < i + 1) {console.setcursorposition (0, i + 1);
                        Console.WriteLine ("{0, -80}", Outputrow); Rows.
                    ADD (Outputrow);
                        else if (Rows[i]!= outputrow) {rows[i] = Outputrow;
                        Console.setcursorposition (0, i + 1);
                    Console.WriteLine ("{0, -80}", Outputrow); }
                }
                If rows. Count > Tablerowcount) {int linestobecleared = rows.
                    Count-tablerowcount; Rows.
                    RemoveRange (Tablerowcount, linestobecleared); for (int i = 0; i < linestobecleared + 1; i++) {Console.WriteLine ("{0,-80
                    }", " ");    } console.setwindowposition (0, Windowtop);
            In order to keep console scroll bar stay thread.sleep (100);
 }
        }
    }
}


The effect is to obtain the status of an active TCP connection per 100ms, that is, approximately 10 times per second, in order to avoid flicker caused by the refresh rate too fast, by calling Console.setcursorposition to partially refresh the changed data. Also, to prevent the scroll bar from being present, the Console pointer causes the scroll bar to scroll automatically to the last line, using setwindowposition to fix the scroll bar position.

Examples of output results:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.