public TcpConnectionInfo(TCP_ESTATS_PATH_ROD_v0 stats, MIB_TCPROW_OWNER_MODULE ownerRow, MIB_TCPROW tcpRow, TCPIP_OWNER_MODULE_BASIC_INFO ownerInfo)
 {
     this.stats     = stats;
     this.ownerRow  = ownerRow;
     this.tcpRow    = tcpRow;
     this.ownerInfo = ownerInfo;
 }
예제 #2
0
파일: TCPHelper.cs 프로젝트: harrwiss/WFN
        internal static Owner GetOwningModuleTCP(MIB_TCPROW_OWNER_MODULE row)
        {
            Owner ret = null;

            /*if (ownerCache.TryGetValue(row, out ret))
             * {
             *  return ret;
             * }*/

            if (row.OwningPid == 0)
            {
                return(Owner.System);
            }

            IntPtr buffer = IntPtr.Zero;

            try
            {
                uint buffSize = 0;
                var  retn     = GetOwnerModuleFromTcpEntry(ref row, TCPIP_OWNER_MODULE_INFO_CLASS.TCPIP_OWNER_MODULE_INFO_BASIC, IntPtr.Zero, ref buffSize);
                if ((retn != NO_ERROR) && (retn != ERROR_INSUFFICIENT_BUFFER))
                {
                    //Cannot get owning module for this connection
                    LogHelper.Info("Unable to get the connection owner: ownerPid=" + row.OwningPid + " remoteAdr=" + row.RemoteAddress + ":" + row.RemotePort);
                    return(ret);
                }
                if (buffSize == 0)
                {
                    //No buffer? Probably means we can't retrieve any information about this connection; skip it
                    LogHelper.Info("Unable to get the connection owner (no buffer).");
                    return(ret);
                }
                buffer = Marshal.AllocHGlobal((int)buffSize);

                //GetOwnerModuleFromTcpEntry needs the fields of TCPIP_OWNER_MODULE_INFO_BASIC to be NULL
                ZeroMemory(buffer, buffSize);

                var resp = GetOwnerModuleFromTcpEntry(ref row, TCPIP_OWNER_MODULE_INFO_CLASS.TCPIP_OWNER_MODULE_INFO_BASIC, buffer, ref buffSize);
                if (resp == 0)
                {
                    ret = new Owner((TCPIP_OWNER_MODULE_BASIC_INFO)Marshal.PtrToStructure(buffer, typeof(TCPIP_OWNER_MODULE_BASIC_INFO)));
                }
                else if (resp != ERROR_NOT_FOUND) // Ignore closed connections
                {
                    LogHelper.Error("Unable to get the connection owner.", new Win32Exception((int)resp));
                }

                //ownerCache.Add(row, ret);

                return(ret);
            }
            finally
            {
                if (buffer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(buffer);
                }
            }
        }
예제 #3
0
        public static TCP_ESTATS_DATA_ROD_v0 GetTCPStatistics(MIB_TCPROW_OWNER_MODULE conn)
        {
            IntPtr rw  = IntPtr.Zero;
            IntPtr rod = IntPtr.Zero;

            try
            {
                var row = new MIB_TCPROW()
                {
                    dwLocalAddr = conn._localAddr, dwRemoteAddr = conn._remoteAddr, dwLocalPort = conn._localPort, dwRemotePort = conn._remotePort, dwState = conn._state
                };

                EnsureStatsAreEnabled(row);

                var rwS = Marshal.SizeOf(typeof(TCP_ESTATS_DATA_RW_v0));
                rw = Marshal.AllocHGlobal(rwS);

                var rodS = Marshal.SizeOf(typeof(TCP_ESTATS_DATA_ROD_v0));
                rod = Marshal.AllocHGlobal(rodS);

                var resp = GetPerTcpConnectionEStats(ref row, TCP_ESTATS_TYPE.TcpConnectionEstatsData, rw, 0, (uint)rwS, IntPtr.Zero, 0, 0, rod, 0, (uint)rodS);
                if (resp != NO_ERROR)
                {
                    LogHelper.Error("Unable to get the connection statistics.", new Win32Exception((int)resp));
                }

                var parsedRW  = (TCP_ESTATS_DATA_RW_v0)Marshal.PtrToStructure(rw, typeof(TCP_ESTATS_DATA_RW_v0));
                var parsedROD = (TCP_ESTATS_DATA_ROD_v0)Marshal.PtrToStructure(rod, typeof(TCP_ESTATS_DATA_ROD_v0));

                return(parsedROD);
            }
            finally
            {
                if (rw != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(rw);
                }

                if (rod != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(rod);
                }
            }
        }
예제 #4
0
 public static extern uint GetOwnerModuleFromTcpEntry(ref MIB_TCPROW_OWNER_MODULE pTcpEntry, TCPIP_OWNER_MODULE_INFO_CLASS Class, IntPtr Buffer, ref uint pdwSize);
예제 #5
0
        public override IEnumerable <CommandDTOBase?> Execute(string[] args)
        {
            var  AF_INET         = 2; // IP_v4
            uint tableBufferSize = 0;
            var  tableBuffer     = IntPtr.Zero;
            var  rowPtr          = IntPtr.Zero;
            var  processes       = new Dictionary <string, string>();

            WriteHost("  Local Address          Foreign Address        State      PID   Service         ProcessName");

            try
            {
                // Adapted from https://stackoverflow.com/questions/577433/which-pid-listens-on-a-given-port-in-c-sharp/577660#577660
                // Build a PID -> process name lookup table
                var searcher            = new ManagementObjectSearcher("SELECT * FROM Win32_Process");
                var retObjectCollection = searcher.Get();

                foreach (ManagementObject Process in retObjectCollection)
                {
                    if (Process["CommandLine"] != null)
                    {
                        processes.Add(Process["ProcessId"].ToString(), Process["CommandLine"].ToString());
                    }
                    else
                    {
                        processes.Add(Process["ProcessId"].ToString(), Process["Name"].ToString());
                    }
                }

                // Figure out how much memory we need for the result struct
                var ret = GetExtendedTcpTable(IntPtr.Zero, ref tableBufferSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_MODULE_ALL, 0);
                if (ret != Win32Error.Success && ret != Win32Error.InsufficientBuffer)
                {
                    // 122 == insufficient buffer size
                    WriteError($"Bad check value from GetExtendedTcpTable : {ret}");
                    yield break;
                }

                tableBuffer = Marshal.AllocHGlobal((int)tableBufferSize);

                ret = GetExtendedTcpTable(tableBuffer, ref tableBufferSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_MODULE_ALL, 0);
                if (ret != Win32Error.Success)
                {
                    WriteError($"Bad return value from GetExtendedTcpTable : {ret}");
                    yield break;
                }

                // get the number of entries in the table
                var ownerModuleTable = (MIB_TCPTABLE_OWNER_MODULE)Marshal.PtrToStructure(tableBuffer, typeof(MIB_TCPTABLE_OWNER_MODULE));
                rowPtr = (IntPtr)(tableBuffer.ToInt64() + Marshal.OffsetOf(typeof(MIB_TCPTABLE_OWNER_MODULE), "Table").ToInt64());
                var TcpRows = new MIB_TCPROW_OWNER_MODULE[ownerModuleTable.NumEntries];

                for (var i = 0; i < ownerModuleTable.NumEntries; i++)
                {
                    var tcpRow =
                        (MIB_TCPROW_OWNER_MODULE)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_MODULE));
                    TcpRows[i] = tcpRow;
                    // next entry
                    rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));
                }

                foreach (var entry in TcpRows)
                {
                    string?processName = null;
                    try
                    {
                        processName = processes[entry.OwningPid.ToString()];
                    }
                    catch { }

                    var serviceName = Advapi32.GetServiceNameFromTag(entry.OwningPid, (uint)entry.OwningModuleInfo0);


                    yield return(new TcpConnectionsDTO(
                                     entry.LocalAddress.ToString(),
                                     entry.LocalPort,
                                     entry.RemoteAddress.ToString(),
                                     entry.RemotePort,
                                     entry.State,
                                     entry.OwningPid,
                                     serviceName,
                                     processName
                                     ));
                }
            }
            finally
            {
                if (tableBuffer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(tableBuffer);
                }
            }
        }
예제 #6
0
 public static extern ErrorCode GetOwnerModuleFromTcpEntry(ref MIB_TCPROW_OWNER_MODULE pTcpEntry, TCPIP_OWNER_MODULE_INFO_CLASS @class, IntPtr buffer, ref int pdwSize);