接收到未知字节

本文关键字:字节 未知 | 更新日期: 2023-09-27 18:26:02

通过我自己的BitReader(逐位读取)捕获IP数据包

public class BitReader
{
    int Index;
    byte Current;
    Stream Reader;
    public BitReader ( Stream Memory )
    {
        Reader = Memory;
    }
    public bool? ReadBit ( )
    {
        if ( Index == 8 )
        {
            Index = 0;
            Current = ( byte ) Reader . ReadByte ( );
        }
        if ( Current == -1 )
        {
            return null;
        }
        else
        {
            return ( Current & ( 1 << ( 7 - Index++ ) ) ) != 0;
         // return ( Current & ( 1 << Index++ ) ) != 0;
        }
    }
}

在IP v4数据包前面接收一个零未知字节,如下所示,

0000000001000101 0000000000000101 11000000 01001001 0010011001000000 00000000 10000000 00000110 10110010 01111110 1100000010101000 0000000 1 00001010 01000101 10101011 11110010 00110101


编辑2:

private byte [ ] Buffer = new byte [ 4096 ];
                    _Socket = new Socket ( AddressFamily . InterNetwork , SocketType . Raw , ProtocolType . IP );
                    _Socket . Bind ( new IPEndPoint ( IPAddress . Parse ( Interface . Text ) , 0 ) );
                    _Socket . SetSocketOption ( SocketOptionLevel . IP , SocketOptionName . HeaderIncluded , true );
                    _Socket . IOControl ( IOControlCode . ReceiveAll , BitConverter . GetBytes ( 1 ) , BitConverter . GetBytes ( 1 ) );
                    _Socket . BeginReceive ( Buffer , 0 , Buffer . Length , SocketFlags . None , new AsyncCallback ( OnReceive ) , null );

编辑1:

MemoryStream _MemoryStream = new MemoryStream ( Buffer , 0 , Length );
BitReader _BitReader = new BitReader ( _MemoryStream );
            for ( int Loop = 0 ; Loop < 21 ; Loop++ )
            {
                bool? Result = _BitReader . ReadBit ( );
                if ( Loop % 8 == 0 && Loop != 0 )
                {
                    myTextBox . Invoke ( new Action ( delegate { myTextBox . Text += " "; } ) );
                }
                if ( Result . HasValue )
                {
                    myTextBox . Invoke ( new Action ( delegate { myTextBox . Text += Result . Value ? 1 : 0; } ) );
                }
            }

编辑3:

MemoryStream _MemoryStream = new MemoryStream(Buffer, 0, Length);
BinaryReader _BinaryReader = new BinaryReader(_MemoryStream );
private byte VersionAndHeaderLength;
VersionAndHeaderLength = _BinaryReader.ReadByte();

接收到未知字节

Index == 0开始,只在Index == 8时读取下一个字节。这意味着您读取的第一个字节将始终为零。要解决此问题,请在构造函数中设置Index = 8

此外,由于byte永远不可能是-1,因此检查Current == -1是否始终是false的条件将在文件末尾获得无限的1 s,因为这是将-1转换为byte时获得的。