0

I have been trying my hand at handling packets and bytes for the first time, and I have not been able to obtain the packet length correctly so far after many different techniques.

Code:

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

So far, all of my attempts at having the console write the data length have resulted in failure. I validated the endianness and actually wrote out the bytes to verify that I was handling the correct data.

Example bytes:

00 00 00 24 -> UINT32 is 36 bytes, but I am getting an array of Integers like 3808493568

How can I fix this?

2
  • 1
    It is big-endian, you need to reverse the bytes. Commented Jun 5, 2014 at 2:17
  • It returns the data length plus the header lengths for the three data layers. I am using WinPCAP by the way Commented Jun 5, 2014 at 2:27

1 Answer 1

1

I agree with Hans, endianness is your problem. Also, I'd recommend you use the BitConverter class on the clientPacket array, easier than using streams.

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

For your code, I think this might work (untested):

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.