Exemple #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());
        }
Exemple #2
0
        /// <summary>
        /// 从流中读取2个字节,并将流内的位置向前推进2个字节,
        /// 返回其UInt16表示类型
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <returns></returns>
        public uint ReadUInt16()
        {
            var range = this.ReadByteRange(sizeof(ushort));

            return(ByteConverter.ToUInt16(range.Buffer, range.Offset, this.Endian));
        }