我怎样才能使用pcapdotnet拆分一个包分成两个包? 这是我试过,但我不知道它是否是正确的:
public IEnumerable<Packet> splitPacket(Packet packet)
{
EthernetLayer ethernet = (EthernetLayer)packet.Ethernet.ExtractLayer();
IpV4Layer ipV4Layer = (IpV4Layer)packet.Ethernet.IpV4.ExtractLayer();
DateTime packetTimestamp = packet.Timestamp;
ILayer payload = packet.Ethernet.IpV4.Payload.ExtractLayer();
IpV4Fragmentation.Equals(packet, packet);
yield return PacketBuilder.Build(packetTimestamp, ethernet, ipV4Layer, payload);
}
我从来没有使用Pcap.Net,所以我不知道这是否会工作,但总的想法是将数据(“有效载荷层”)拆分成若干块,然后将其发送。 为了确保该片段可以被重新组装,您还需要添加有关每个片段的位置( 偏移 )的一些信息。
在Pcap.Net中, IpV4Fragmentation
类里包含了这两个属性:
-
IpV4Fragmentation.Options
: - 对于除塔最后一个的所有片段,它应被设置为
IpV4FragmentationOptions.MoreFragments
, - 对于最后一个片段,它应被设置为
IpV4FragmentationOptions.None
-
IpV4Fragmentation.Offset
: - 的片段(其必须是8的倍数)的包含的偏移。 该偏移是用于第一片段为零。
考虑到这一点,我会写这样的事情:
(免责声明:本写在记事本中,我不知道如果它甚至编译,更不用说工作,因为它应该):
public IEnumerable<Packet> Split(Packet packet, int numberOfFragments)
{
// get original layers
var ethernet = (EthernetLayer)packet.Ethernet.ExtractLayer();
var ipV4 = (IpV4Layer)packet.Ethernet.IpV4.ExtractLayer();
var time = packet.Timestamp;
// extract the data
var payload = (PayloadLayer)packet.Ethernet.IpV4.Payload.ExtractLayer();
var totalLength = payload.Length;
// split data into smaller segments
var partialLength = totalLength / numberOfFragments;
// make sure it's divisible with 8
// (see http://en.wikipedia.org/wiki/IPv4#Fragmentation_and_reassembly)
partialLength = (partialLength / 8) * 8;
// send one by one
var offset = 0;
while (offset < totalLength)
{
// get length for this fragment
var fragmentLength = partialLength;
var options = IpV4FragmentationOptions.MoreFragments;
// is this the last fragment? trim length if needed
if (offset + fragmentLength >= totalLength)
{
options = IpV4FragmentationOptions.None;
fragmentLength = totalLength - offset;
}
// copy the actual data into a new buffer
var newBuffer = payload.ReadBytes(offset, fragmentLength);
var newPayload = new PayloadLayer() { Data = newBuffer };
// change IP layer fragmentation options
ipV4.Fragmentation = new IpV4Fragmentation(options, offset);
// return it
yield return PacketBuilder.Build(time, ethernet, ipV4, newPayload);
// next offset
offset += fragmentLength;
}
}
[更新了@ brickner的建议]