Home › Forums › Discussions › Support › Help for VB.Net users – Reading data with managed code
- This topic has 0 replies, 1 voice, and was last updated 16 years, 2 months ago by HennieP.
-
AuthorPosts
-
September 13, 2008 at 4:17 pm #5227
Hello,
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_PACKETDim 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 FunctionAs 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.
-
AuthorPosts
- You must be logged in to reply to this topic.