Search code examples
c#ipv4packet-capture

Unknown Byte Received


Capturing IP Packets by my own BitReader ( Reading Bit By Bit )

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;
        }
    }
}

Receiving a ZERO unknown byte in front of IP v4 Packets, as shown below,

00000000 01000101 00000000 00000101 11000000 01001001 00100110 01000000 00000000 10000000 00000110 10110010 01111110 11000000 10101000 00000001 00001010 01000101 10101011 11110010 00110101


Edit 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 );

Edit 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; } ) );
                }
            }

Edit 3 :

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

Solution

  • You start with Index == 0 and only read the next byte when Index == 8. This means that the first byte you read will be always zero. To fix this, set Index = 8 in your constructor.

    Also, since byte can never be -1, the condition that checks whether Current == -1 will be always false and you will get infinite 1s at the end of the file, because that's what you get when converting -1 to byte.