通过我自己的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数据包前接收ZERO未知字节,如下所示
00000000 01000101 00000000 00000101 11000000 01001001 00100110 01000000 00000000 10000000 00000110 10110010 01111110 11000000 10101000 00000001 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();
答案 0 :(得分:2)
您从Index == 0
开始,仅在Index == 8
时读取下一个字节。这意味着您读取的第一个字节将始终为零。要解决此问题,请在构造函数中设置Index = 8
。
此外,由于byte
永远不能为-1,因此检查Current == -1
是否始终为false
并且您将在结束时获得无限1
的条件该文件,因为这是将-1
转换为byte
时的结果。