Esempio n. 1
0
        /// <summary>
        /// 获取一次Tcp端口快照信息
        /// </summary>
        /// <param name="ipVersion">ip版本</param>
        /// <returns></returns>
        public unsafe static PortOwnerPid[] Snapshot(AddressFamily ipVersion)
        {
            var size = 0;
            var TCP_TABLE_OWNER_PID_ALL = 5;

            TcpSnapshot.GetExtendedTcpTable(null, &size, false, ipVersion, TCP_TABLE_OWNER_PID_ALL, 0);

            var pTable = stackalloc byte[size];
            var state  = TcpSnapshot.GetExtendedTcpTable(pTable, &size, false, ipVersion, TCP_TABLE_OWNER_PID_ALL, 0);

            if (state != 0)
            {
                return(new PortOwnerPid[0]);
            }

            var hashSet   = new HashSet <PortOwnerPid>();
            var rowLength = *(int *)(pTable);
            var pRow      = pTable + Marshal.SizeOf(rowLength);

            for (int i = 0; i < rowLength; i++)
            {
                var row  = *(MIB_TCPROW_OWNER_PID *)pRow;
                var port = ByteConverter.ToBytes(row.LocalPort, Endians.Little);

                var portOwner = new PortOwnerPid
                {
                    Port    = ByteConverter.ToUInt16(port, 0, Endians.Big),
                    OwerPid = (int)row.OwningPid
                };
                hashSet.Add(portOwner);
                pRow = pRow + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID));
            }

            return(hashSet.OrderBy(item => item.Port).ToArray());
        }
Esempio n. 2
0
 /// <summary>
 /// 获取一次IPv4的Tcp端口快照信息
 /// </summary>
 /// <returns></returns>
 public unsafe static PortOwnerPid[] Snapshot()
 {
     return(TcpSnapshot.Snapshot(AddressFamily.InterNetwork));
 }