What can I do with tcp Payload?

Apr 17, 2010 at 2:39 PM

Hi,

my receive function is:  

private void OnReceive(Packet packet)

{

	IpV4Datagram ipPacket = packet.Ethernet.IpV4;

	TcpDatagram tcpPacket = ipPacket.Tcp;

}
Now I need to have the data that arrives with tcpPacket.
How can I do it?

Coordinator
Apr 17, 2010 at 3:38 PM

The TCP data is available by calling the Payload property:

 

 

private void OnReceive(Packet packet)
{
	IpV4Datagram ipPacket = packet.Ethernet.IpV4;
	TcpDatagram tcpPacket = ipPacket.Tcp;
	Datagram tcpData = tcpPacket.Payload;
}

Boaz.

 

Apr 17, 2010 at 9:43 PM

Yes, I know, but what can I do with Datagram class instance?

It doesn't have many members (let's assume, I don't want to play with inheritance).

Coordinator
Apr 18, 2010 at 6:28 AM

First, Datagram is an IEnumerable<byte>, so you can enumerate its bytes.

Second, it implements the [] operator, so you can access each byte by calling it with the offset in the TCP payload offset.

Third, if you want to use it differently, I can expand its interface. Let me know what you need.

 

Boaz.

Apr 18, 2010 at 9:15 AM

Thanks for your interest. I used to use it like that:

MemoryStream memoryStream = new MemoryStream(PacketPayload, 0, nReceived);
				
BinaryReader binaryReader = new BinaryReader(memoryStream);
int type = binaryReader.ReadInt32();

PacketPayload is an array of bytes. With binary reader it is handy to use.

Thanks.

 

Coordinator
Apr 18, 2010 at 10:43 AM

For now, you can:

1. Create a byte[] and write to it by enumerating the Datagram's bytes or by accessing them using the [] operator.

2. Create a MemoryStream and write to it using the same methods.

 

I'll try to see if I can create a method that gives the Datagram as a read only MemoryStream.

Coordinator
Apr 19, 2010 at 3:01 PM

I've added ToMemoryStream() method to the Datagram class.

It gives you a read only MemoryStream object you can use to read any Datagram.

It will be included in the next Pcap.Net version.

Meanwhile, you can download the latest source code, and any version from changeset 40520 would include this feature.

Jun 8, 2011 at 4:00 AM
Edited Jun 8, 2011 at 4:03 AM

On that subject, it would be nice to have a .ToArray() to get the whole buffer, or byte[] Copy( int startIndex, int count ) to get a portion of the payload.

Strange design decision to return a memory stream. And by the way, if we use ToMemoryStream(), do we dispose the stream or it's an internal stream that you dispose internally?

Coordinator
Jun 9, 2011 at 2:14 PM

The idea behind the ToMemoryStream() is that it's efficient and doesn't cause a full copy.

The Datagram is read only and cannot be changed. I prefer not to give a trivial method that will cause a full copy.

Note that you can still do ToArray() because it's an extension method of IEnumerable<T> in .NET.