题
我一直在首次在处理数据包和字节时尝试,并且在许多不同的技术之后,我无法正确地获得数据包长度。
代码:
Public Shared Sub Client(packet As Packet)
Console.WriteLine( _
"Client -> " & _
packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") & _
" length:" & Convert.ToString(packet.Length))
'Define Byte Array
Dim clientPacket As Byte() = packet.Buffer
' Open a Binary Reader
Dim memStream As MemoryStream = New MemoryStream(clientPacket)
Dim bReader As BinaryReader = New BinaryReader(memStream)
' Remove the Ethernet Header
Dim ethBytes As Byte() = bReader.ReadBytes(14)
' Remove the IPv4 Header
Dim IPv4Bytes As Byte() = bReader.ReadBytes(20)
' Remove the TCP Header
Dim TCPBytes As Byte() = bReader.ReadBytes(20)
' Get the packet length
If clientPacket.Length > 54 Then
Dim len As UInt32 = bReader.ReadUInt32
Console.WriteLine(len)
End If
End Sub
.
到目前为止,我的所有尝试都在控制台写入数据长度导致失败。我验证了endianness,实际上写出了字节来验证我是否正在处理正确的数据。
示例字节:
00 00 00 00 00 00 2 - > UINT32是36字节,但我得到了一个整数的数组,如3808493568
如何解决这个问题?
解决方案
我同意汉斯,endianness是你的问题。此外,我建议您在BitConverter
阵列上使用clientPacket
类,而不是使用流。
Dim len As UInt32
Dim arr() As Byte
arr = {0, 0, 0, 24}
len = BitConverter.ToUInt32(arr, 0)
Console.Write(len.ToString) 'returns 402653184
arr = {24, 0, 0, 0}
len = BitConverter.ToUInt32(arr, 0)
Console.Write(len.ToString) 'returns 24
.
对于您的代码,我认为这可能会有效(未经测试):
If clientPacket.Length > 54 Then
Dim lenBytes As Byte() = bReader.ReadBytes(4)
Array.Reverse(lenBytes, 0, 4)
Dim len As UInt32 = BitConverter.ToUInt32(lenBytes, 0)
. 不隶属于 StackOverflow