바이트 ()에서 .NET에서 부호없는 정수로
-
21-12-2019 - |
문제
나는 패킷을 처음으로 취급 할 때 손을 노력하고 있으며, 나는 많은 다른 기술 이후로 패킷 길이를 올바르게 얻을 수 없었습니다.
코드 :
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
.
지금까지 콘솔을 쓸 때의 모든 시도가 데이터 길이를 작성하게되었습니다.나는 엔디안을 유효화하고 실제로 올바른 데이터를 처리했는지 확인하기 위해 실제로 바이트를 썼습니다.
예제 바이트 :
00 00 00 00 24 -> UINT32는 36 바이트이지만 3808493568
와 같은 정수 배열을 얻고 있습니다.어떻게 해결할 수 있습니까?
해결책
나는 한스에 동의하며, 엔디안은 당신의 문제입니다.또한 The 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