Пример #1
0
        public Boolean Capture()
        {
            try
            {
                _socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
                var inBytes  = new Byte[] { 1, 0, 0, 0 };
                var outBytes = new Byte[] { 0, 0, 0, 0 };
                _socket.IOControl(IOControlCode.ReceiveAll, inBytes, outBytes);
                if (0 != outBytes[0] + outBytes[1] + outBytes[2] + outBytes[3])
                {
                    return(false);
                }
            }
            catch (SocketException)
            {
                return(false);
            }

            while (_socket != null)
            {
                var buffer = new Byte[1500];

                var count = _socket.Receive(buffer, SocketFlags.None);
                var pk    = new Packet(buffer, 0, count);

                OnReceive?.Invoke(buffer, count);

                if (OnTcpReceive != null)
                {
                    var ip = new IPPacket(pk);
                    if (ip.Protocol == ProtocolType.Tcp)
                    {
                        var tcp = new TcpPacket(ip);
                        OnTcpReceive(tcp);
                    }
                }
            }

            return(true);
        }
Пример #2
0
        public TcpPacket(IPPacket packet)
        {
            if (packet == null)
            {
                throw new ArgumentNullException(nameof(packet));
            }
            if (packet.Protocol != ProtocolType.Tcp)
            {
                throw new NotSupportedException();
            }

            IPPacket = packet;

            var pk   = packet.Data;
            var data = pk.ReadBytes(0, 20);

            SrcPort  = (UInt16)((data[0] << 8) + data[1]);
            DestPort = (UInt16)((data[2] << 8) + data[3]);

            SequenceNo = ((UInt32)data[7] << 24) + ((UInt32)data[6] << 16) + ((UInt32)data[5] << 8) + data[4];
            NextSeqNo  = ((UInt32)data[11] << 24) + ((UInt32)data[10] << 16) + ((UInt32)data[9] << 8) + data[8];

            HeadLength = (Byte)(((data[12] & 0xF0) >> 4) * 4);

            // 6bit保留位
            Flag       = (Byte)(data[13] & 0x3F);
            WindowSize = (UInt16)((data[14] << 8) + data[15]);
            CheckSum   = (UInt16)((data[16] << 8) + data[17]);
            UrgPtr     = (UInt16)((data[18] << 8) + data[19]);

            // 可选项
            if (HeadLength > 20)
            {
                Option = pk.ReadBytes(20, HeadLength - 20);
            }

            Data = pk.Sub(HeadLength);
        }