Domanda

Ho provato la mia mano a gestire pacchetti e byte per la prima volta, e non sono stato in grado di ottenere la lunghezza del pacchetto correttamente finora dopo molte tecniche diverse.

Codice:

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
.

Finora, tutti i miei tentativi di avere la console scrivere la lunghezza dei dati ha portato a un fallimento.Ho convalidato l'Edianness e ho effettivamente scritto i byte per verificare che stavo maneggiando i dati corretti.

Esempio Bytes:

00 00 00 24 -> UINT32 è 36 byte, ma sto ottenendo una serie di numeri interi come 3808493568

Come posso risolvere questo?

È stato utile?

Soluzione

Sono d'accordo con Hans, l'Edianness è il tuo problema.Inoltre, ti consiglierei di utilizzare la classe BitConverter sull'array clientPacket, è più semplice dall'uso di flussi.

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
.

Per il tuo codice, penso che questo potrebbe funzionare (non testato):

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)
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top