Help for VB.Net users – Reading data with managed code

Home Forums Discussions Support Portal Help for VB.Net users – Reading data with managed code

This topic contains 0 replies, has 1 voice, and was last updated by  HennieP 9 years, 10 months ago.

Viewing 1 post (of 1 total)
  • Author
  • #5227



    I am currently devloping a frontend for a small firewall app and I just want to share a few tips with other VB.Net users.

    Here is a way to read the Packet data in managed code.
    Public Function ReadIPPacket(ByVal ReadBuffer() As Byte) As IP_PACKET

    Dim MemStream As New MemoryStream(ReadBuffer, ETHER_HEADER_LEN, 32)
    Dim BinReader As New BinaryReader(MemStream)
    Dim IPPacket As New IP_PACKET()

    IPPacket.Version = BinReader.ReadByte()
    IPPacket.HeaderLength = ((IPPacket.Version And &HF) * 4)
    IPPacket.TypeOfService = BinReader.ReadByte()
    IPPacket.TotalLength = UShortNTOHS(BinReader.ReadUInt16())
    IPPacket.Identification = UShortNTOHS(BinReader.ReadUInt16())
    IPPacket.FragmentOffset = UShortNTOHS(BinReader.ReadUInt16())
    IPPacket.TimeToLive = BinReader.ReadByte()
    IPPacket.Protocol = BinReader.ReadByte()
    IPPacket.HeaderChecksum = UShortNTOHS(BinReader.ReadUInt16())
    IPPacket.SourceAddress = New IPAddress(BinReader.ReadUInt32())
    IPPacket.DestinationAddress = New IPAddress(BinReader.ReadUInt32())
    IPPacket.PacketData = BinReader.ReadBytes(IPPacket.TotalLength – IPPacket.HeaderLength)

    Return IPPacket
    End Function

    As you can see, we use the System.IO.MemoryStream and System.IO.BinaryReader to read data in perfectly managed code. This approach may seem like a lot of work but you end up writing less code in your main app if you do it this way. It doesn’t copy memory around from unmaged space to managed and back like Marshal.Copy would for instance and you don’t have to worry about freeing up pointers from memory either.

    UShortNTOHS is the ntohs function that comes with the samples. The System.Net.Ipaddress.NetworkToHostOrder function does NOT work with unsigned shorts and you get weird results with anything other than UShort so stick to this.

    So there you have it. Just one approach to solving the problem. It works very well for me. Feel free to share your expereince in this.

    This method can be used in C# too of course.

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.