Quantcast
Channel: PcapDotNet Wiki & Documentation Rss Feed
Viewing all 114 articles
Browse latest View live

Updated Wiki: Pcap.Net Tutorial - Handling offline dump files

$
0
0

Handling offline dump files

In this lession we are going to learn how to handle packet capture to a file (dump to file). Pcap.Net offers a wide range of functions to save the network traffic to a file and to read the content of dumps -- this lesson will teach how to use all of these functions.

The format for dump files is the libpcap one. This format contains the data of the captured packets in binary form and is a standard used by many network tools including WinDump, Ethereal and Snort.

Saving packets to a dump file

First of all, let's see how to write packets in libpcap format.

The following example captures the packets from the selected interface and saves them on a file whose name is provided by the user.

using System;
using System.Collections.Generic;
using PcapDotNet.Core;

namespace SavingPacketsToADumpFile
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Check command lineif (args.Length != 1)
            {
                Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " <filename>");
                return;
            }

            // Retrieve the device list on the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the listfor (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[deviceIndex - 1];

            // Open the deviceusing (PacketCommunicator communicator =
                selectedDevice.Open(65536, // portion of the packet to capture// 65536 guarantees that the whole packet will be captured on all the link layers
                                    PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                    1000)) // read timeout
            {
                // Open the dump fileusing (PacketDumpFile dumpFile = communicator.OpenDump(args[0]))
                {
                    Console.WriteLine("Listening on " + selectedDevice.Description + "... Press Ctrl+C to stop...");

                    // start the capture
                    communicator.ReceivePackets(0, dumpFile.Dump);
                }
            }
        }
    }
}

As you can see, the structure of the program is very similar to the ones we have seen in the previous lessons. The differences are:
  • A call to OpenDump() is issued once the interface is opened. This call opens a dump file and associates it with the interface.
  • The packets are written to this file by setting the callback to the dump file's Dump() method. A different approach would be to give a specially created method for as a callback or an anonymous delegate.

Reading packets from a dump file

Now that we have a dump file available, we can try to read its content. The following code opens a libpcap dump file and displays every packet contained in the file. The file is opened with Open(), then the usual ReceivePackets() is used to sequence through the packets. As you can see, reading packets from an offline capture is nearly identical to receiving them from a physical interface.

using System;
using PcapDotNet.Core;
using PcapDotNet.Packets;

namespace ReadingPacketsFromADumpFile
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Send anonymous statistics about the usage of Pcap.Net
            PcapDotNet.Analysis.PcapDotNetAnalysis.OptIn = true;

            // Check command lineif (args.Length != 1)
            {
                Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " <filename>");
                return;
            }

            // Create the offline device
            OfflinePacketDevice selectedDevice = new OfflinePacketDevice(args[0]);

            // Open the capture fileusing (PacketCommunicator communicator =
                selectedDevice.Open(65536,                                  // portion of the packet to capture// 65536 guarantees that the whole packet will be captured on all the link layers
                                    PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                    1000))                                  // read timeout
            {
                // Read and dispatch packets until EOF is reached
                communicator.ReceivePackets(0, DispatcherHandler);
            }
        }

        privatestaticvoid DispatcherHandler(Packet packet)
        {
            // print packet timestamp and packet length
            Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length);

            // Print the packetconstint LineLength = 64;
            for (int i = 0; i != packet.Length; ++i)
            {
                Console.Write((packet[i]).ToString("X2"));
                if ((i + 1) % LineLength == 0)
                  Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine();
        }
    }
}

<<< PreviousNext >>>

Updated Wiki: Pcap.Net Tutorial - Handling offline dump files

$
0
0

Handling offline dump files

In this lession we are going to learn how to handle packet capture to a file (dump to file). Pcap.Net offers a wide range of functions to save the network traffic to a file and to read the content of dumps -- this lesson will teach how to use all of these functions.

The format for dump files is the libpcap one. This format contains the data of the captured packets in binary form and is a standard used by many network tools including WinDump, Ethereal and Snort.

Saving packets to a dump file

First of all, let's see how to write packets in libpcap format.

The following example captures the packets from the selected interface and saves them on a file whose name is provided by the user.

using System;
using System.Collections.Generic;
using PcapDotNet.Core;

namespace SavingPacketsToADumpFile
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Check command lineif (args.Length != 1)
            {
                Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " <filename>");
                return;
            }

            // Retrieve the device list on the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the listfor (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[deviceIndex - 1];

            // Open the deviceusing (PacketCommunicator communicator =
                selectedDevice.Open(65536, // portion of the packet to capture// 65536 guarantees that the whole packet will be captured on all the link layers
                                    PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                    1000)) // read timeout
            {
                // Open the dump fileusing (PacketDumpFile dumpFile = communicator.OpenDump(args[0]))
                {
                    Console.WriteLine("Listening on " + selectedDevice.Description + "... Press Ctrl+C to stop...");

                    // start the capture
                    communicator.ReceivePackets(0, dumpFile.Dump);
                }
            }
        }
    }
}

As you can see, the structure of the program is very similar to the ones we have seen in the previous lessons. The differences are:
  • A call to OpenDump() is issued once the interface is opened. This call opens a dump file and associates it with the interface.
  • The packets are written to this file by setting the callback to the dump file's Dump() method. A different approach would be to give a specially created method for as a callback or an anonymous delegate.

Reading packets from a dump file

Now that we have a dump file available, we can try to read its content. The following code opens a libpcap dump file and displays every packet contained in the file. The file is opened with Open(), then the usual ReceivePackets() is used to sequence through the packets. As you can see, reading packets from an offline capture is nearly identical to receiving them from a physical interface.

using System;
using PcapDotNet.Core;
using PcapDotNet.Packets;

namespace ReadingPacketsFromADumpFile
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Check command lineif (args.Length != 1)
            {
                Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " <filename>");
                return;
            }

            // Create the offline device
            OfflinePacketDevice selectedDevice = new OfflinePacketDevice(args[0]);

            // Open the capture fileusing (PacketCommunicator communicator =
                selectedDevice.Open(65536,                                  // portion of the packet to capture// 65536 guarantees that the whole packet will be captured on all the link layers
                                    PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                    1000))                                  // read timeout
            {
                // Read and dispatch packets until EOF is reached
                communicator.ReceivePackets(0, DispatcherHandler);
            }
        }

        privatestaticvoid DispatcherHandler(Packet packet)
        {
            // print packet timestamp and packet length
            Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length);

            // Print the packetconstint LineLength = 64;
            for (int i = 0; i != packet.Length; ++i)
            {
                Console.Write((packet[i]).ToString("X2"));
                if ((i + 1) % LineLength == 0)
                  Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine();
        }
    }
}

<<< PreviousNext >>>

Updated Wiki: Pcap.Net Tutorial - Sending Packets

$
0
0

Sending Packets

Although the name Pcap.Net indicates clearly that the purpose of the library is packet capture, other useful features for raw networking are provided. Among them, the user can find a complete set of functions to send packets.

Note that the original libpcap library at the moment doesn't provide any way to send packets, therefore all the functions shown here are Pcap.Net extensions based on WinPcap extensions and will not work under Unix.

Sending a single packet with SendPacket()

The simplest way to send a packet is shown in the following code snippet. After opening an adapter, SendPacket() is called to send a hand-crafted packet. SendPacket() takes as argument the packet containing the data to send. Notice that the packet is sent to the net as is, without any manipulation. This means that the application has to create the correct protocol headers in order to send something meaningful.

This code uses SendPacket() to send 100 Ping (ICMP Echo) packets to different IPv4 destinations, with different IPv4 IDs, different ICMP Sequence Numbers and different ICMP Identifiers. This is done by creating a PacketBuilder instance with Ethernet, IPv4 and ICMP Echo layers, and by changing the layers' properties' values for each packet.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PcapDotNet.Base;
using PcapDotNet.Core;
using PcapDotNet.Packets;
using PcapDotNet.Packets.Arp;
using PcapDotNet.Packets.Dns;
using PcapDotNet.Packets.Ethernet;
using PcapDotNet.Packets.Gre;
using PcapDotNet.Packets.Http;
using PcapDotNet.Packets.Icmp;
using PcapDotNet.Packets.Igmp;
using PcapDotNet.Packets.IpV4;
using PcapDotNet.Packets.Transport;

namespace SendingASinglePacketWithSendPacket
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Retrieve the device list from the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the listfor (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[deviceIndex - 1];

            // Open the output deviceusing (PacketCommunicator communicator = selectedDevice.Open(100, // name of the device
                                                                         PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                                                         1000)) // read timeout
            {
                // Supposing to be on ethernet, set mac source to 01:01:01:01:01:01
                MacAddress source = new MacAddress("01:01:01:01:01:01");

                // set mac destination to 02:02:02:02:02:02
                MacAddress destination = new MacAddress("02:02:02:02:02:02");

                // Create the packets layers// Ethernet Layer
                EthernetLayer ethernetLayer = new EthernetLayer
                                                  {
                                                      Source = source,
                                                      Destination = destination
                                                  };

                // IPv4 Layer
                IpV4Layer ipV4Layer = new IpV4Layer
                                          {
                                              Source = new IpV4Address("1.2.3.4"),
                                              Ttl = 128,
                                              // The rest of the important parameters will be set for each packet
                                          };

                // ICMP Layer
                IcmpEchoLayer icmpLayer = new IcmpEchoLayer();

                // Create the builder that will build our packets
                PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);

                // Send 100 Pings to different destination with different parametersfor (int i = 0; i != 100; ++i)
                {
                    // Set IPv4 parameters
                    ipV4Layer.CurrentDestination = new IpV4Address("2.3.4." + i);
                    ipV4Layer.Identification = (ushort)i;

                    // Set ICMP parameters
                    icmpLayer.SequenceNumber = (ushort)i;
                    icmpLayer.Identifier = (ushort)i;

                    // Build the packet
                    Packet packet = builder.Build(DateTime.Now);

                    // Send down the packet
                    communicator.SendPacket(packet);
                }

                communicator.SendPacket(BuildEthernetPacket());
                communicator.SendPacket(BuildArpPacket());
                communicator.SendPacket(BuildVLanTaggedFramePacket());
                communicator.SendPacket(BuildIpV4Packet());
                communicator.SendPacket(BuildIcmpPacket());
                communicator.SendPacket(BuildIgmpPacket());
                communicator.SendPacket(BuildGrePacket());
                communicator.SendPacket(BuildUdpPacket());
                communicator.SendPacket(BuildTcpPacket());
                communicator.SendPacket(BuildDnsPacket());
                communicator.SendPacket(BuildHttpPacket());
                communicator.SendPacket(BuildComplexPacket());
            }
        }

        ///<summary>/// This function build an Ethernet with payload packet.///</summary>privatestatic Packet BuildEthernetPacket()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("01:01:01:01:01:01"),
                                                  Destination = new MacAddress("02:02:02:02:02:02"),
                                                  EtherType = EthernetType.IpV4,
                                              };

            PayloadLayer payloadLayer = new PayloadLayer
                                            {
                                                Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                                            };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an ARP over Ethernet packet.///</summary>privatestatic Packet BuildArpPacket()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("01:01:01:01:01:01"),
                                                  Destination = new MacAddress("02:02:02:02:02:02"),
                                                  EtherType = EthernetType.None, // Will be filled automatically.
                                              };

            ArpLayer arpLayer = new ArpLayer
                                    {
                                        ProtocolType = EthernetType.IpV4,
                                        Operation = ArpOperation.Request,
                                        SenderHardwareAddress = newbyte[] {3, 3, 3, 3, 3, 3}.AsReadOnly(), // 03:03:03:03:03:03.
                                        SenderProtocolAddress = newbyte[] {1, 2, 3, 4}.AsReadOnly(), // 1.2.3.4.
                                        TargetHardwareAddress = newbyte[] {4, 4, 4, 4, 4, 4}.AsReadOnly(), // 04:04:04:04:04:04.
                                        TargetProtocolAddress = newbyte[] {11, 22, 33, 44}.AsReadOnly(), // 11.22.33.44.
                                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build a VLanTaggedFrame over Ethernet with payload packet.///</summary>privatestatic Packet BuildVLanTaggedFramePacket()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("01:01:01:01:01:01"),
                                                  Destination = new MacAddress("02:02:02:02:02:02"),
                                                  EtherType = EthernetType.None, // Will be filled automatically.
                                              };

            VLanTaggedFrameLayer vLanTaggedFrameLayer = new VLanTaggedFrameLayer
                                                            {
                                                                PriorityCodePoint = ClassOfService.Background,
                                                                CanonicalFormatIndicator = false,
                                                                VLanIdentifier = 50,
                                                                EtherType = EthernetType.IpV4,
                                                            };

            PayloadLayer payloadLayer = new PayloadLayer
                                            {
                                                Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                                            };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, vLanTaggedFrameLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an IPv4 over Ethernet with payload packet.///</summary>privatestatic Packet BuildIpV4Packet()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("01:01:01:01:01:01"),
                                                  Destination = new MacAddress("02:02:02:02:02:02"),
                                                  EtherType = EthernetType.None,
                                              };

            IpV4Layer ipV4Layer = new IpV4Layer
                                      {
                                          Source = new IpV4Address("1.2.3.4"),
                                          CurrentDestination = new IpV4Address("11.22.33.44"),
                                          Fragmentation = IpV4Fragmentation.None,
                                          HeaderChecksum = null, // Will be filled automatically.
                                          Identification = 123,
                                          Options = IpV4Options.None,
                                          Protocol = IpV4Protocol.Udp,
                                          Ttl = 100,
                                          TypeOfService = 0,
                                      };

            PayloadLayer payloadLayer = new PayloadLayer
                                            {
                                                Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                                            };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an ICMP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildIcmpPacket()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("01:01:01:01:01:01"),
                                                  Destination = new MacAddress("02:02:02:02:02:02"),
                                                  EtherType = EthernetType.None, // Will be filled automatically.
                                              };

            IpV4Layer ipV4Layer = new IpV4Layer
                                      {
                                          Source = new IpV4Address("1.2.3.4"),
                                          CurrentDestination = new IpV4Address("11.22.33.44"),
                                          Fragmentation = IpV4Fragmentation.None,
                                          HeaderChecksum = null, // Will be filled automatically.
                                          Identification = 123,
                                          Options = IpV4Options.None,
                                          Protocol = null, // Will be filled automatically.
                                          Ttl = 100,
                                          TypeOfService = 0,
                                      };

            IcmpEchoLayer icmpLayer = new IcmpEchoLayer
                                          {
                                              Checksum = null, // Will be filled automatically.
                                              Identifier = 456,
                                              SequenceNumber = 800,
                                          };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an IGMP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildIgmpPacket()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("01:01:01:01:01:01"),
                                                  Destination = new MacAddress("02:02:02:02:02:02"),
                                                  EtherType = EthernetType.None, // Will be filled automatically.
                                              };

            IpV4Layer ipV4Layer = new IpV4Layer
                                      {
                                          Source = new IpV4Address("1.2.3.4"),
                                          CurrentDestination = new IpV4Address("11.22.33.44"),
                                          Fragmentation = IpV4Fragmentation.None,
                                          HeaderChecksum = null, // Will be filled automatically.
                                          Identification = 123,
                                          Options = IpV4Options.None,
                                          Protocol = null, // Will be filled automatically.
                                          Ttl = 100,
                                          TypeOfService = 0,
                                      };

            IgmpQueryVersion1Layer igmpLayer = new IgmpQueryVersion1Layer
                                                   {
                                                       GroupAddress = new IpV4Address("1.2.3.4"),
                                                   };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, igmpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an IPv4 over GRE over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildGrePacket()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("01:01:01:01:01:01"),
                                                  Destination = new MacAddress("02:02:02:02:02:02"),
                                                  EtherType = EthernetType.None, // Will be filled automatically.
                                              };

            IpV4Layer ipV4Layer = new IpV4Layer
                                      {
                                          Source = new IpV4Address("1.2.3.4"),
                                          CurrentDestination = new IpV4Address("11.22.33.44"),
                                          Fragmentation = IpV4Fragmentation.None,
                                          HeaderChecksum = null, // Will be filled automatically.
                                          Identification = 123,
                                          Options = IpV4Options.None,
                                          Protocol = null, // Will be filled automatically.
                                          Ttl = 100,
                                          TypeOfService = 0,
                                      };

            GreLayer greLayer = new GreLayer
                                    {
                                        Version = GreVersion.Gre,
                                        ProtocolType = EthernetType.None, // Will be filled automatically.
                                        RecursionControl = 0,
                                        FutureUseBits = 0,
                                        ChecksumPresent = true,
                                        Checksum = null, // Will be filled automatically.
                                        Key = null,
                                        SequenceNumber = 123,
                                        AcknowledgmentSequenceNumber = null,
                                        RoutingOffset = null,
                                        Routing = null,
                                        StrictSourceRoute = false,
                                    };

            IpV4Layer innerIpV4Layer = new IpV4Layer
                                           {
                                               Source = new IpV4Address("100.200.201.202"),
                                               CurrentDestination = new IpV4Address("123.254.132.40"),
                                               Fragmentation = IpV4Fragmentation.None,
                                               HeaderChecksum = null, // Will be filled automatically.
                                               Identification = 123,
                                               Options = IpV4Options.None,
                                               Protocol = IpV4Protocol.Udp,
                                               Ttl = 120,
                                               TypeOfService = 0,
                                           };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, greLayer, innerIpV4Layer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an UDP over IPv4 over Ethernet with payload packet.///</summary>privatestatic Packet BuildUdpPacket()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("01:01:01:01:01:01"),
                                                  Destination = new MacAddress("02:02:02:02:02:02"),
                                                  EtherType = EthernetType.None, // Will be filled automatically.
                                              };

            IpV4Layer ipV4Layer = new IpV4Layer
                                      {
                                          Source = new IpV4Address("1.2.3.4"),
                                          CurrentDestination = new IpV4Address("11.22.33.44"),
                                          Fragmentation = IpV4Fragmentation.None,
                                          HeaderChecksum = null, // Will be filled automatically.
                                          Identification = 123,
                                          Options = IpV4Options.None,
                                          Protocol = null, // Will be filled automatically.
                                          Ttl = 100,
                                          TypeOfService = 0,
                                      };

            UdpLayer udpLayer = new UdpLayer
                                    {
                                        SourcePort = 4050,
                                        DestinationPort = 25,
                                        Checksum = null, // Will be filled automatically.
                                        CalculateChecksumValue = true,
                                    };

            PayloadLayer payloadLayer = new PayloadLayer
                                            {
                                                Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                                            };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an TCP over IPv4 over Ethernet with payload packet.///</summary>privatestatic Packet BuildTcpPacket()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("01:01:01:01:01:01"),
                                                  Destination = new MacAddress("02:02:02:02:02:02"),
                                                  EtherType = EthernetType.None, // Will be filled automatically.
                                              };

            IpV4Layer ipV4Layer = new IpV4Layer
                                      {
                                          Source = new IpV4Address("1.2.3.4"),
                                          CurrentDestination = new IpV4Address("11.22.33.44"),
                                          Fragmentation = IpV4Fragmentation.None,
                                          HeaderChecksum = null, // Will be filled automatically.
                                          Identification = 123,
                                          Options = IpV4Options.None,
                                          Protocol = null, // Will be filled automatically.
                                          Ttl = 100,
                                          TypeOfService = 0,
                                      };

            TcpLayer tcpLayer = new TcpLayer()
                                    {
                                        SourcePort = 4050,
                                        DestinationPort = 25,
                                        Checksum = null, // Will be filled automatically.
                                        SequenceNumber = 100,
                                        AcknowledgmentNumber = 50,
                                        ControlBits = TcpControlBits.Acknowledgment,
                                        Window = 100,
                                        UrgentPointer = 0,
                                        Options = TcpOptions.None,
                                    };

            PayloadLayer payloadLayer = new PayloadLayer
                                            {
                                                Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                                            };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }
        
        ///<summary>/// This function build a DNS over UDP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildDnsPacket()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("01:01:01:01:01:01"),
                                                  Destination = new MacAddress("02:02:02:02:02:02"),
                                                  EtherType = EthernetType.None, // Will be filled automatically.
                                              };

            IpV4Layer ipV4Layer = new IpV4Layer
                                      {
                                          Source = new IpV4Address("1.2.3.4"),
                                          CurrentDestination = new IpV4Address("11.22.33.44"),
                                          Fragmentation = IpV4Fragmentation.None,
                                          HeaderChecksum = null, // Will be filled automatically.
                                          Identification = 123,
                                          Options = IpV4Options.None,
                                          Protocol = null, // Will be filled automatically.
                                          Ttl = 100,
                                          TypeOfService = 0,
                                      };

            UdpLayer udpLayer = new UdpLayer
                                    {
                                        SourcePort = 4050,
                                        DestinationPort = 53,
                                        Checksum = null, // Will be filled automatically.
                                        CalculateChecksumValue = true,
                                    };

            DnsLayer dnsLayer = new DnsLayer
                                    {
                                        Id = 100,
                                        IsResponse = false,
                                        OpCode = DnsOpCode.Query,
                                        IsAuthoritativeAnswer = false,
                                        IsTruncated = false,
                                        IsRecursionDesired = true,
                                        IsRecursionAvailable = false,
                                        FutureUse = false,
                                        IsAuthenticData = false,
                                        IsCheckingDisabled = false,
                                        ResponseCode = DnsResponseCode.NoError,
                                        Queries = new[] {new DnsQueryResourceRecord(new DnsDomainName("pcapdot.net"), DnsType.A, DnsClass.Internet),},
                                        Answers = null,
                                        Authorities = null,
                                        Additionals = null,
                                        DomainNameCompressionMode = DnsDomainNameCompressionMode.All,
                                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, dnsLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an HTTP over TCP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildHttpPacket()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("01:01:01:01:01:01"),
                                                  Destination = new MacAddress("02:02:02:02:02:02"),
                                                  EtherType = EthernetType.None, // Will be filled automatically.
                                              };

            IpV4Layer ipV4Layer = new IpV4Layer
                                      {
                                          Source = new IpV4Address("1.2.3.4"),
                                          CurrentDestination = new IpV4Address("11.22.33.44"),
                                          Fragmentation = IpV4Fragmentation.None,
                                          HeaderChecksum = null, // Will be filled automatically.
                                          Identification = 123,
                                          Options = IpV4Options.None,
                                          Protocol = null, // Will be filled automatically.
                                          Ttl = 100,
                                          TypeOfService = 0,
                                      };

            TcpLayer tcpLayer = new TcpLayer
                                    {
                                        SourcePort = 4050,
                                        DestinationPort = 80,
                                        Checksum = null, // Will be filled automatically.
                                        SequenceNumber = 100,
                                        AcknowledgmentNumber = 50,
                                        ControlBits = TcpControlBits.Acknowledgment,
                                        Window = 100,
                                        UrgentPointer = 0,
                                        Options = TcpOptions.None,
                                    };

            HttpRequestLayer httpLayer = new HttpRequestLayer
                                             {
                                                 Version = HttpVersion.Version11,
                                                 Header = new HttpHeader(new HttpContentLengthField(11)),
                                                 Body = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                                                 Method = new HttpRequestMethod(HttpRequestKnownMethod.Get),
                                                 Uri = @"http://pcapdot.net/",
                                             };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, httpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build a DNS over UDP over IPv4 over GRE over IPv4 over IPv4 over VLAN Tagged Frame over VLAN Tagged Frame over Ethernet.///</summary>privatestatic Packet BuildComplexPacket()
        {
            return PacketBuilder.Build(
                DateTime.Now,
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    },
                new VLanTaggedFrameLayer
                    {
                        PriorityCodePoint = ClassOfService.ExcellentEffort,
                        CanonicalFormatIndicator = false,
                        EtherType = EthernetType.None, // Will be filled automatically.
                    },
                new VLanTaggedFrameLayer
                    {
                        PriorityCodePoint = ClassOfService.BestEffort,
                        CanonicalFormatIndicator = false,
                        EtherType = EthernetType.None, // Will be filled automatically.
                    },
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    },
                new IpV4Layer
                    {
                        Source = new IpV4Address("5.6.7.8"),
                        CurrentDestination = new IpV4Address("55.66.77.88"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 456,
                        Options = new IpV4Options(new IpV4OptionStrictSourceRouting(new[]
                                                                                        {
                                                                                            new IpV4Address("100.200.100.200"),
                                                                                            new IpV4Address("150.250.150.250")
                                                                                        }, 1)),
                        Protocol = null, // Will be filled automatically.
                        Ttl = 200,
                        TypeOfService = 0,
                    },
                new GreLayer
                    {
                        Version = GreVersion.Gre,
                        ProtocolType = EthernetType.None, // Will be filled automatically.
                        RecursionControl = 0,
                        FutureUseBits = 0,
                        ChecksumPresent = true,
                        Checksum = null, // Will be filled automatically.
                        Key = 100,
                        SequenceNumber = 123,
                        AcknowledgmentSequenceNumber = null,
                        RoutingOffset = null,
                        Routing = new[]
                                      {
                                          new GreSourceRouteEntryIp(new[]
                                                                        {
                                                                            new IpV4Address("10.20.30.40"),
                                                                            new IpV4Address("40.30.20.10")
                                                                        }.AsReadOnly(), 1),
                                          new GreSourceRouteEntryIp(new[]
                                                                        {
                                                                            new IpV4Address("11.22.33.44"),
                                                                            new IpV4Address("44.33.22.11")
                                                                        }.AsReadOnly(), 0)
                                      }.Cast<GreSourceRouteEntry>().ToArray().AsReadOnly(),
                        StrictSourceRoute = false,
                    },
                new IpV4Layer
                    {
                        Source = new IpV4Address("51.52.53.54"),
                        CurrentDestination = new IpV4Address("61.62.63.64"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = new IpV4Options(new IpV4OptionTimestampOnly(0, 1,
                                                                              new IpV4TimeOfDay(new TimeSpan(1, 2, 3)),
                                                                              new IpV4TimeOfDay(new TimeSpan(15, 55, 59))),
                                                  new IpV4OptionQuickStart(IpV4OptionQuickStartFunction.RateRequest, 10, 200, 300)),
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    },
                new UdpLayer
                    {
                        SourcePort = 53,
                        DestinationPort = 40101,
                        Checksum = null, // Will be filled automatically.
                        CalculateChecksumValue = true,
                    },
                new DnsLayer
                    {
                        Id = 10012,
                        IsResponse = true,
                        OpCode = DnsOpCode.Query,
                        IsAuthoritativeAnswer = true,
                        IsTruncated = false,
                        IsRecursionDesired = true,
                        IsRecursionAvailable = true,
                        FutureUse = false,
                        IsAuthenticData = true,
                        IsCheckingDisabled = false,
                        ResponseCode = DnsResponseCode.NoError,
                        Queries = new[] {new DnsQueryResourceRecord(new DnsDomainName("pcapdot.net"), DnsType.Any, DnsClass.Internet),},
                        Answers = new[]
                                      {
                                          new DnsDataResourceRecord(new DnsDomainName("pcapdot.net"), DnsType.A, DnsClass.Internet, 50000,
                                                                    new DnsResourceDataIpV4(new IpV4Address("10.20.30.44"))),
                                          new DnsDataResourceRecord(new DnsDomainName("pcapdot.net"), DnsType.Txt, DnsClass.Internet, 50000,
                                                                    new DnsResourceDataText(new[] {new DataSegment(Encoding.ASCII.GetBytes("Pcap.Net"))}.AsReadOnly()))
                                      },
                        Authorities = new[]
                                          {
                                              new DnsDataResourceRecord(new DnsDomainName("pcapdot.net"), DnsType.MailExchange, DnsClass.Internet, 100,
                                                                        new DnsResourceDataMailExchange(100, new DnsDomainName("pcapdot.net")))
                                          },
                        Additionals = new[]
                                          {
                                              new DnsOptResourceRecord(new DnsDomainName("pcapdot.net"), 50000, 0, DnsOptVersion.Version0, DnsOptFlags.DnsSecOk,
                                                                       new DnsResourceDataOptions(new DnsOptions(new DnsOptionUpdateLease(100),
                                                                                                                 new DnsOptionLongLivedQuery(1, DnsLongLivedQueryOpCode.Refresh, DnsLongLivedQueryErrorCode.NoError, 10, 20))))
                                          },
                        DomainNameCompressionMode = DnsDomainNameCompressionMode.All,
                    });
        }
    }
}

Sending packets using Send Buffer

While SendPacket() offers a simple and immediate way to send a single packet, send buffers provides an advanced, powerful and optimized mechanism to send a collection of packets. A send buffer is a container for a variable number of packets that will be sent to the network. It has a size, that represents the maximum amount of bytes it can store.

A send buffer is created calling the PacketSendBuffer constructor, specifying the size of the new send buffer.

Once the send buffer is created, Enqueue() can be used to add a packet to the send buffer. This function takes a packet with data and timestamp.

To transmit a send buffer, Pcap.Net provides the Transmit() method. Note the second parameter: if true, the send will be synchronized, i.e. the relative timestamps of the packets will be respected. This operation requires a remarkable amount of CPU, because the synchronization takes place in the kernel driver using "busy wait" loops. Although this operation is quite CPU intensive, it often results in very high precision packet transmissions (often around few microseconds or less).

Note that transmitting a send buffer with Transmit() is much more efficient than performing a series of SendPacket(), because the send buffer is buffered at kernel level drastically decreasing the number of context switches.

When a send buffer is no longer needed, it shoudl be disposed by calling Dispose() that frees all the buffers associated with the send buffer.

The next program shows how to use send buffers. It opens a capture file, then it moves the packets from the file to a properly allocated send buffer. At this point it transmits the buffer, synchronizing it if requested by the user.

Note that the link-layer of the dumpfile is compared with the one of the interface that will send the packets using DataLink, and a warning is printed if they are different -- it is important that the capture-file link-layer be the same as the adapter's link layer for otherwise the transmission is pointless.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using PcapDotNet.Core;
using PcapDotNet.Packets;

namespace SendingPacketsUsingSendBuffer
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Send anonymous statistics about the usage of Pcap.Net
            PcapDotNet.Analysis.PcapDotNetAnalysis.OptIn = true;

            // Check the validity of the command lineif (args.Length == 0 || args.Length > 2)
            {
                Usage();
                return;
            }

            // Retrieve the device list from the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the listfor (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedOutputDevice = allDevices[deviceIndex - 1];

            // Retrieve the length of the capture filelong capLength = new FileInfo(args[0]).Length;

            // Chek if the timestamps must be respectedbool isSync = (args.Length == 2 && args[1][0] == 's');

            // Open the capture file
            OfflinePacketDevice selectedInputDevice = new OfflinePacketDevice(args[0]);

            using (PacketCommunicator inputCommunicator =
                selectedInputDevice.Open(65536, // portion of the packet to capture// 65536 guarantees that the whole packet will be captured on all the link layers
                                         PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                         1000)) // read timeout
            {
                using (PacketCommunicator outputCommunicator =
                    selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    // Check the MAC typeif (inputCommunicator.DataLink != outputCommunicator.DataLink)
                    {
                        Console.WriteLine(
                            "Warning: the datalink of the capture differs from the one of the selected interface.");
                        Console.WriteLine("Press a key to continue, or CTRL+C to stop.");
                        Console.ReadKey();
                    }

                    // Allocate a send bufferusing (PacketSendBuffer sendBuffer = new PacketSendBuffer((uint)capLength))
                    {
                        // Fill the buffer with the packets from the fileint numPackets = 0;
                        Packet packet;
                        while (inputCommunicator.ReceivePacket(out packet) == PacketCommunicatorReceiveResult.Ok)
                        {
                            sendBuffer.Enqueue(packet);
                            ++numPackets;
                        }

                        // Transmit the queue
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();
                        long startTimeMs = stopwatch.ElapsedMilliseconds;
                        Console.WriteLine("Start Time: " + startTimeMs);
                        outputCommunicator.Transmit(sendBuffer, isSync);
                        long endTimeMs = stopwatch.ElapsedMilliseconds;
                        Console.WriteLine("End Time: " + endTimeMs);
                        long elapsedTimeMs = endTimeMs - startTimeMs;
                        Console.WriteLine("Elapsed Time: " + elapsedTimeMs);
                        double averagePacketsPerSecond = elapsedTimeMs == 0 ? double.MaxValue : (double)numPackets / elapsedTimeMs * 1000;

                        Console.WriteLine("Elapsed time: " + elapsedTimeMs + " ms");
                        Console.WriteLine("Total packets generated = " + numPackets);
                        Console.WriteLine("Average packets per second = " + averagePacketsPerSecond);
                        Console.WriteLine();
                    }
                }
            }
        }

        privatestaticvoid Usage()
        {
            Console.WriteLine("Sends a libpcap/tcpdump capture file to the net.");
            Console.WriteLine("Usage:");
            Console.WriteLine("\t" + Environment.GetCommandLineArgs()[0] + " <filename> [s]");
            Console.WriteLine();
            Console.WriteLine("Parameters:");
            Console.WriteLine("\tfilename: the name of the dump file that will be sent to the network");
            Console.WriteLine(
                "\ts: if present, forces the packets to be sent synchronously, i.e. respecting the timestamps in the dump file. This option will work only under Windows NTx");
        }
    }
}

<<< PreviousNext >>>

Updated Wiki: Pcap.Net Tutorial - Sending Packets

$
0
0

Sending Packets

Although the name Pcap.Net indicates clearly that the purpose of the library is packet capture, other useful features for raw networking are provided. Among them, the user can find a complete set of functions to send packets.

Note that the original libpcap library at the moment doesn't provide any way to send packets, therefore all the functions shown here are Pcap.Net extensions based on WinPcap extensions and will not work under Unix.

Sending a single packet with SendPacket()

The simplest way to send a packet is shown in the following code snippet. After opening an adapter, SendPacket() is called to send a hand-crafted packet. SendPacket() takes as argument the packet containing the data to send. Notice that the packet is sent to the net as is, without any manipulation. This means that the application has to create the correct protocol headers in order to send something meaningful.

This code uses SendPacket() to send 100 Ping (ICMP Echo) packets to different IPv4 destinations, with different IPv4 IDs, different ICMP Sequence Numbers and different ICMP Identifiers. This is done by creating a PacketBuilder instance with Ethernet, IPv4 and ICMP Echo layers, and by changing the layers' properties' values for each packet.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PcapDotNet.Base;
using PcapDotNet.Core;
using PcapDotNet.Packets;
using PcapDotNet.Packets.Arp;
using PcapDotNet.Packets.Dns;
using PcapDotNet.Packets.Ethernet;
using PcapDotNet.Packets.Gre;
using PcapDotNet.Packets.Http;
using PcapDotNet.Packets.Icmp;
using PcapDotNet.Packets.Igmp;
using PcapDotNet.Packets.IpV4;
using PcapDotNet.Packets.Transport;

namespace SendingASinglePacketWithSendPacket
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Retrieve the device list from the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the listfor (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[deviceIndex - 1];

            // Open the output deviceusing (PacketCommunicator communicator = selectedDevice.Open(100, // name of the device
                                                                         PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                                                         1000)) // read timeout
            {
                // Supposing to be on ethernet, set mac source to 01:01:01:01:01:01
                MacAddress source = new MacAddress("01:01:01:01:01:01");

                // set mac destination to 02:02:02:02:02:02
                MacAddress destination = new MacAddress("02:02:02:02:02:02");

                // Create the packets layers// Ethernet Layer
                EthernetLayer ethernetLayer = new EthernetLayer
                                                  {
                                                      Source = source,
                                                      Destination = destination
                                                  };

                // IPv4 Layer
                IpV4Layer ipV4Layer = new IpV4Layer
                                          {
                                              Source = new IpV4Address("1.2.3.4"),
                                              Ttl = 128,
                                              // The rest of the important parameters will be set for each packet
                                          };

                // ICMP Layer
                IcmpEchoLayer icmpLayer = new IcmpEchoLayer();

                // Create the builder that will build our packets
                PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);

                // Send 100 Pings to different destination with different parametersfor (int i = 0; i != 100; ++i)
                {
                    // Set IPv4 parameters
                    ipV4Layer.CurrentDestination = new IpV4Address("2.3.4." + i);
                    ipV4Layer.Identification = (ushort)i;

                    // Set ICMP parameters
                    icmpLayer.SequenceNumber = (ushort)i;
                    icmpLayer.Identifier = (ushort)i;

                    // Build the packet
                    Packet packet = builder.Build(DateTime.Now);

                    // Send down the packet
                    communicator.SendPacket(packet);
                }

                communicator.SendPacket(BuildEthernetPacket());
                communicator.SendPacket(BuildArpPacket());
                communicator.SendPacket(BuildVLanTaggedFramePacket());
                communicator.SendPacket(BuildIpV4Packet());
                communicator.SendPacket(BuildIcmpPacket());
                communicator.SendPacket(BuildIgmpPacket());
                communicator.SendPacket(BuildGrePacket());
                communicator.SendPacket(BuildUdpPacket());
                communicator.SendPacket(BuildTcpPacket());
                communicator.SendPacket(BuildDnsPacket());
                communicator.SendPacket(BuildHttpPacket());
                communicator.SendPacket(BuildComplexPacket());
            }
        }

        ///<summary>/// This function build an Ethernet with payload packet.///</summary>privatestatic Packet BuildEthernetPacket()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = new MacAddress("01:01:01:01:01:01"),
                                                  Destination = new MacAddress("02:02:02:02:02:02"),
                                                  EtherType = EthernetType.IpV4,
                                              };

            PayloadLayer payloadLayer = new PayloadLayer
                                            {
                                                Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                                            };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an ARP over Ethernet packet.///</summary>privatestatic Packet BuildArpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            ArpLayer arpLayer =
                new ArpLayer
                    {
                        ProtocolType = EthernetType.IpV4,
                        Operation = ArpOperation.Request,
                        SenderHardwareAddress = newbyte[] {3, 3, 3, 3, 3, 3}.AsReadOnly(), // 03:03:03:03:03:03.
                        SenderProtocolAddress = newbyte[] {1, 2, 3, 4}.AsReadOnly(), // 1.2.3.4.
                        TargetHardwareAddress = newbyte[] {4, 4, 4, 4, 4, 4}.AsReadOnly(), // 04:04:04:04:04:04.
                        TargetProtocolAddress = newbyte[] {11, 22, 33, 44}.AsReadOnly(), // 11.22.33.44.
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build a VLanTaggedFrame over Ethernet with payload packet.///</summary>privatestatic Packet BuildVLanTaggedFramePacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            VLanTaggedFrameLayer vLanTaggedFrameLayer =
                new VLanTaggedFrameLayer
                    {
                        PriorityCodePoint = ClassOfService.Background,
                        CanonicalFormatIndicator = false,
                        VLanIdentifier = 50,
                        EtherType = EthernetType.IpV4,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, vLanTaggedFrameLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an IPv4 over Ethernet with payload packet.///</summary>privatestatic Packet BuildIpV4Packet()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None,
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = IpV4Protocol.Udp,
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an ICMP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildIcmpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            IcmpEchoLayer icmpLayer =
                new IcmpEchoLayer
                    {
                        Checksum = null, // Will be filled automatically.
                        Identifier = 456,
                        SequenceNumber = 800,
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an IGMP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildIgmpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            IgmpQueryVersion1Layer igmpLayer =
                new IgmpQueryVersion1Layer
                    {
                        GroupAddress = new IpV4Address("1.2.3.4"),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, igmpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an IPv4 over GRE over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildGrePacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            GreLayer greLayer =
                new GreLayer
                    {
                        Version = GreVersion.Gre,
                        ProtocolType = EthernetType.None, // Will be filled automatically.
                        RecursionControl = 0,
                        FutureUseBits = 0,
                        ChecksumPresent = true,
                        Checksum = null, // Will be filled automatically.
                        Key = null,
                        SequenceNumber = 123,
                        AcknowledgmentSequenceNumber = null,
                        RoutingOffset = null,
                        Routing = null,
                        StrictSourceRoute = false,
                    };

            IpV4Layer innerIpV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("100.200.201.202"),
                        CurrentDestination = new IpV4Address("123.254.132.40"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = IpV4Protocol.Udp,
                        Ttl = 120,
                        TypeOfService = 0,
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, greLayer, innerIpV4Layer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an UDP over IPv4 over Ethernet with payload packet.///</summary>privatestatic Packet BuildUdpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            UdpLayer udpLayer =
                new UdpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 25,
                        Checksum = null, // Will be filled automatically.
                        CalculateChecksumValue = true,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an TCP over IPv4 over Ethernet with payload packet.///</summary>privatestatic Packet BuildTcpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            TcpLayer tcpLayer =
                new TcpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 25,
                        Checksum = null, // Will be filled automatically.
                        SequenceNumber = 100,
                        AcknowledgmentNumber = 50,
                        ControlBits = TcpControlBits.Acknowledgment,
                        Window = 100,
                        UrgentPointer = 0,
                        Options = TcpOptions.None,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }
        
        ///<summary>/// This function build a DNS over UDP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildDnsPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            UdpLayer udpLayer =
                new UdpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 53,
                        Checksum = null, // Will be filled automatically.
                        CalculateChecksumValue = true,
                    };

            DnsLayer dnsLayer =
                new DnsLayer
                    {
                        Id = 100,
                        IsResponse = false,
                        OpCode = DnsOpCode.Query,
                        IsAuthoritativeAnswer = false,
                        IsTruncated = false,
                        IsRecursionDesired = true,
                        IsRecursionAvailable = false,
                        FutureUse = false,
                        IsAuthenticData = false,
                        IsCheckingDisabled = false,
                        ResponseCode = DnsResponseCode.NoError,
                        Queries = new[]
                                      {
                                          new DnsQueryResourceRecord(new DnsDomainName("pcapdot.net"),
                                                                     DnsType.A,
                                                                     DnsClass.Internet),
                                      },
                        Answers = null,
                        Authorities = null,
                        Additionals = null,
                        DomainNameCompressionMode = DnsDomainNameCompressionMode.All,
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, dnsLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an HTTP over TCP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildHttpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            TcpLayer tcpLayer =
                new TcpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 80,
                        Checksum = null, // Will be filled automatically.
                        SequenceNumber = 100,
                        AcknowledgmentNumber = 50,
                        ControlBits = TcpControlBits.Acknowledgment,
                        Window = 100,
                        UrgentPointer = 0,
                        Options = TcpOptions.None,
                    };

            HttpRequestLayer httpLayer =
                new HttpRequestLayer
                    {
                        Version = HttpVersion.Version11,
                        Header = new HttpHeader(new HttpContentLengthField(11)),
                        Body = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                        Method = new HttpRequestMethod(HttpRequestKnownMethod.Get),
                        Uri = @"http://pcapdot.net/",
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, httpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build a DNS over UDP over IPv4 over GRE over IPv4 over IPv4 over VLAN Tagged Frame over VLAN Tagged Frame over Ethernet.///</summary>privatestatic Packet BuildComplexPacket()
        {
            return PacketBuilder.Build(
                DateTime.Now,
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    },
                new VLanTaggedFrameLayer
                    {
                        PriorityCodePoint = ClassOfService.ExcellentEffort,
                        CanonicalFormatIndicator = false,
                        EtherType = EthernetType.None, // Will be filled automatically.
                    },
                new VLanTaggedFrameLayer
                    {
                        PriorityCodePoint = ClassOfService.BestEffort,
                        CanonicalFormatIndicator = false,
                        EtherType = EthernetType.None, // Will be filled automatically.
                    },
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    },
                new IpV4Layer
                    {
                        Source = new IpV4Address("5.6.7.8"),
                        CurrentDestination = new IpV4Address("55.66.77.88"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 456,
                        Options = new IpV4Options(new IpV4OptionStrictSourceRouting(
                                                      new[]
                                                          {
                                                              new IpV4Address("100.200.100.200"),
                                                              new IpV4Address("150.250.150.250")
                                                          }, 1)),
                        Protocol = null, // Will be filled automatically.
                        Ttl = 200,
                        TypeOfService = 0,
                    },
                new GreLayer
                    {
                        Version = GreVersion.Gre,
                        ProtocolType = EthernetType.None, // Will be filled automatically.
                        RecursionControl = 0,
                        FutureUseBits = 0,
                        ChecksumPresent = true,
                        Checksum = null, // Will be filled automatically.
                        Key = 100,
                        SequenceNumber = 123,
                        AcknowledgmentSequenceNumber = null,
                        RoutingOffset = null,
                        Routing = new[]
                                      {
                                          new GreSourceRouteEntryIp(
                                              new[]
                                                  {
                                                      new IpV4Address("10.20.30.40"),
                                                      new IpV4Address("40.30.20.10")
                                                  }.AsReadOnly(), 1),
                                          new GreSourceRouteEntryIp(
                                              new[]
                                                  {
                                                      new IpV4Address("11.22.33.44"),
                                                      new IpV4Address("44.33.22.11")
                                                  }.AsReadOnly(), 0)
                                      }.Cast<GreSourceRouteEntry>().ToArray().AsReadOnly(),
                        StrictSourceRoute = false,
                    },
                new IpV4Layer
                    {
                        Source = new IpV4Address("51.52.53.54"),
                        CurrentDestination = new IpV4Address("61.62.63.64"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = new IpV4Options(
                            new IpV4OptionTimestampOnly(0, 1,
                                                        new IpV4TimeOfDay(new TimeSpan(1, 2, 3)),
                                                        new IpV4TimeOfDay(new TimeSpan(15, 55, 59))),
                            new IpV4OptionQuickStart(IpV4OptionQuickStartFunction.RateRequest, 10, 200, 300)),
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    },
                new UdpLayer
                    {
                        SourcePort = 53,
                        DestinationPort = 40101,
                        Checksum = null, // Will be filled automatically.
                        CalculateChecksumValue = true,
                    },
                new DnsLayer
                    {
                        Id = 10012,
                        IsResponse = true,
                        OpCode = DnsOpCode.Query,
                        IsAuthoritativeAnswer = true,
                        IsTruncated = false,
                        IsRecursionDesired = true,
                        IsRecursionAvailable = true,
                        FutureUse = false,
                        IsAuthenticData = true,
                        IsCheckingDisabled = false,
                        ResponseCode = DnsResponseCode.NoError,
                        Queries =
                            new[]
                                {
                                    new DnsQueryResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        DnsType.Any,
                                        DnsClass.Internet),
                                },
                        Answers =
                            new[]
                                {
                                    new DnsDataResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        DnsType.A,
                                        DnsClass.Internet
                                        , 50000,
                                        new DnsResourceDataIpV4(new IpV4Address("10.20.30.44"))),
                                    new DnsDataResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        DnsType.Txt,
                                        DnsClass.Internet,
                                        50000,
                                        new DnsResourceDataText(new[] {new DataSegment(Encoding.ASCII.GetBytes("Pcap.Net"))}.AsReadOnly()))
                                },
                        Authorities =
                            new[]
                                {
                                    new DnsDataResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        DnsType.MailExchange,
                                        DnsClass.Internet,
                                        100,
                                        new DnsResourceDataMailExchange(100, new DnsDomainName("pcapdot.net")))
                                },
                        Additionals =
                            new[]
                                {
                                    new DnsOptResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        50000,
                                        0,
                                        DnsOptVersion.Version0,
                                        DnsOptFlags.DnsSecOk,
                                        new DnsResourceDataOptions(
                                            new DnsOptions(
                                                new DnsOptionUpdateLease(100),
                                                new DnsOptionLongLivedQuery(1,
                                                                            DnsLongLivedQueryOpCode.Refresh,
                                                                            DnsLongLivedQueryErrorCode.NoError,
                                                                            10, 20))))
                                },
                        DomainNameCompressionMode = DnsDomainNameCompressionMode.All,
                    });
        }
    }
}

Sending packets using Send Buffer

While SendPacket() offers a simple and immediate way to send a single packet, send buffers provides an advanced, powerful and optimized mechanism to send a collection of packets. A send buffer is a container for a variable number of packets that will be sent to the network. It has a size, that represents the maximum amount of bytes it can store.

A send buffer is created calling the PacketSendBuffer constructor, specifying the size of the new send buffer.

Once the send buffer is created, Enqueue() can be used to add a packet to the send buffer. This function takes a packet with data and timestamp.

To transmit a send buffer, Pcap.Net provides the Transmit() method. Note the second parameter: if true, the send will be synchronized, i.e. the relative timestamps of the packets will be respected. This operation requires a remarkable amount of CPU, because the synchronization takes place in the kernel driver using "busy wait" loops. Although this operation is quite CPU intensive, it often results in very high precision packet transmissions (often around few microseconds or less).

Note that transmitting a send buffer with Transmit() is much more efficient than performing a series of SendPacket(), because the send buffer is buffered at kernel level drastically decreasing the number of context switches.

When a send buffer is no longer needed, it shoudl be disposed by calling Dispose() that frees all the buffers associated with the send buffer.

The next program shows how to use send buffers. It opens a capture file, then it moves the packets from the file to a properly allocated send buffer. At this point it transmits the buffer, synchronizing it if requested by the user.

Note that the link-layer of the dumpfile is compared with the one of the interface that will send the packets using DataLink, and a warning is printed if they are different -- it is important that the capture-file link-layer be the same as the adapter's link layer for otherwise the transmission is pointless.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using PcapDotNet.Core;
using PcapDotNet.Packets;

namespace SendingPacketsUsingSendBuffer
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Send anonymous statistics about the usage of Pcap.Net
            PcapDotNet.Analysis.PcapDotNetAnalysis.OptIn = true;

            // Check the validity of the command lineif (args.Length == 0 || args.Length > 2)
            {
                Usage();
                return;
            }

            // Retrieve the device list from the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the listfor (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedOutputDevice = allDevices[deviceIndex - 1];

            // Retrieve the length of the capture filelong capLength = new FileInfo(args[0]).Length;

            // Chek if the timestamps must be respectedbool isSync = (args.Length == 2 && args[1][0] == 's');

            // Open the capture file
            OfflinePacketDevice selectedInputDevice = new OfflinePacketDevice(args[0]);

            using (PacketCommunicator inputCommunicator =
                selectedInputDevice.Open(65536, // portion of the packet to capture// 65536 guarantees that the whole packet will be captured on all the link layers
                                         PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                         1000)) // read timeout
            {
                using (PacketCommunicator outputCommunicator =
                    selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    // Check the MAC typeif (inputCommunicator.DataLink != outputCommunicator.DataLink)
                    {
                        Console.WriteLine(
                            "Warning: the datalink of the capture differs from the one of the selected interface.");
                        Console.WriteLine("Press a key to continue, or CTRL+C to stop.");
                        Console.ReadKey();
                    }

                    // Allocate a send bufferusing (PacketSendBuffer sendBuffer = new PacketSendBuffer((uint)capLength))
                    {
                        // Fill the buffer with the packets from the fileint numPackets = 0;
                        Packet packet;
                        while (inputCommunicator.ReceivePacket(out packet) == PacketCommunicatorReceiveResult.Ok)
                        {
                            sendBuffer.Enqueue(packet);
                            ++numPackets;
                        }

                        // Transmit the queue
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();
                        long startTimeMs = stopwatch.ElapsedMilliseconds;
                        Console.WriteLine("Start Time: " + startTimeMs);
                        outputCommunicator.Transmit(sendBuffer, isSync);
                        long endTimeMs = stopwatch.ElapsedMilliseconds;
                        Console.WriteLine("End Time: " + endTimeMs);
                        long elapsedTimeMs = endTimeMs - startTimeMs;
                        Console.WriteLine("Elapsed Time: " + elapsedTimeMs);
                        double averagePacketsPerSecond = elapsedTimeMs == 0 ? double.MaxValue : (double)numPackets / elapsedTimeMs * 1000;

                        Console.WriteLine("Elapsed time: " + elapsedTimeMs + " ms");
                        Console.WriteLine("Total packets generated = " + numPackets);
                        Console.WriteLine("Average packets per second = " + averagePacketsPerSecond);
                        Console.WriteLine();
                    }
                }
            }
        }

        privatestaticvoid Usage()
        {
            Console.WriteLine("Sends a libpcap/tcpdump capture file to the net.");
            Console.WriteLine("Usage:");
            Console.WriteLine("\t" + Environment.GetCommandLineArgs()[0] + " <filename> [s]");
            Console.WriteLine();
            Console.WriteLine("Parameters:");
            Console.WriteLine("\tfilename: the name of the dump file that will be sent to the network");
            Console.WriteLine(
                "\ts: if present, forces the packets to be sent synchronously, i.e. respecting the timestamps in the dump file. This option will work only under Windows NTx");
        }
    }
}

<<< PreviousNext >>>

Updated Wiki: Pcap.Net Tutorial - Sending Packets

$
0
0

Sending Packets

Although the name Pcap.Net indicates clearly that the purpose of the library is packet capture, other useful features for raw networking are provided. Among them, the user can find a complete set of functions to send packets.

Note that the original libpcap library at the moment doesn't provide any way to send packets, therefore all the functions shown here are Pcap.Net extensions based on WinPcap extensions and will not work under Unix.

Sending a single packet with SendPacket()

The simplest way to send a packet is shown in the following code snippet. After opening an adapter, SendPacket() is called to send a hand-crafted packet. SendPacket() takes as argument the packet containing the data to send. Notice that the packet is sent to the net as is, without any manipulation. This means that the application has to create the correct protocol headers in order to send something meaningful.

This code uses SendPacket() to send 100 Ping (ICMP Echo) packets to different IPv4 destinations, with different IPv4 IDs, different ICMP Sequence Numbers and different ICMP Identifiers. This is done by creating a PacketBuilder instance with Ethernet, IPv4 and ICMP Echo layers, and by changing the layers' properties' values for each packet.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PcapDotNet.Base;
using PcapDotNet.Core;
using PcapDotNet.Packets;
using PcapDotNet.Packets.Arp;
using PcapDotNet.Packets.Dns;
using PcapDotNet.Packets.Ethernet;
using PcapDotNet.Packets.Gre;
using PcapDotNet.Packets.Http;
using PcapDotNet.Packets.Icmp;
using PcapDotNet.Packets.Igmp;
using PcapDotNet.Packets.IpV4;
using PcapDotNet.Packets.Transport;

namespace SendingASinglePacketWithSendPacket
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Retrieve the device list from the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the listfor (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[deviceIndex - 1];

            // Open the output deviceusing (PacketCommunicator communicator = selectedDevice.Open(100, // name of the device
                                                                         PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                                                         1000)) // read timeout
            {
                // Supposing to be on ethernet, set mac source to 01:01:01:01:01:01
                MacAddress source = new MacAddress("01:01:01:01:01:01");

                // set mac destination to 02:02:02:02:02:02
                MacAddress destination = new MacAddress("02:02:02:02:02:02");

                // Create the packets layers// Ethernet Layer
                EthernetLayer ethernetLayer = new EthernetLayer
                                                  {
                                                      Source = source,
                                                      Destination = destination
                                                  };

                // IPv4 Layer
                IpV4Layer ipV4Layer = new IpV4Layer
                                          {
                                              Source = new IpV4Address("1.2.3.4"),
                                              Ttl = 128,
                                              // The rest of the important parameters will be set for each packet
                                          };

                // ICMP Layer
                IcmpEchoLayer icmpLayer = new IcmpEchoLayer();

                // Create the builder that will build our packets
                PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);

                // Send 100 Pings to different destination with different parametersfor (int i = 0; i != 100; ++i)
                {
                    // Set IPv4 parameters
                    ipV4Layer.CurrentDestination = new IpV4Address("2.3.4." + i);
                    ipV4Layer.Identification = (ushort)i;

                    // Set ICMP parameters
                    icmpLayer.SequenceNumber = (ushort)i;
                    icmpLayer.Identifier = (ushort)i;

                    // Build the packet
                    Packet packet = builder.Build(DateTime.Now);

                    // Send down the packet
                    communicator.SendPacket(packet);
                }

                communicator.SendPacket(BuildEthernetPacket());
                communicator.SendPacket(BuildArpPacket());
                communicator.SendPacket(BuildVLanTaggedFramePacket());
                communicator.SendPacket(BuildIpV4Packet());
                communicator.SendPacket(BuildIcmpPacket());
                communicator.SendPacket(BuildIgmpPacket());
                communicator.SendPacket(BuildGrePacket());
                communicator.SendPacket(BuildUdpPacket());
                communicator.SendPacket(BuildTcpPacket());
                communicator.SendPacket(BuildDnsPacket());
                communicator.SendPacket(BuildHttpPacket());
                communicator.SendPacket(BuildComplexPacket());
            }
        }

        ///<summary>/// This function build an Ethernet with payload packet.///</summary>privatestatic Packet BuildEthernetPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.IpV4,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an ARP over Ethernet packet.///</summary>privatestatic Packet BuildArpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            ArpLayer arpLayer =
                new ArpLayer
                    {
                        ProtocolType = EthernetType.IpV4,
                        Operation = ArpOperation.Request,
                        SenderHardwareAddress = newbyte[] {3, 3, 3, 3, 3, 3}.AsReadOnly(), // 03:03:03:03:03:03.
                        SenderProtocolAddress = newbyte[] {1, 2, 3, 4}.AsReadOnly(), // 1.2.3.4.
                        TargetHardwareAddress = newbyte[] {4, 4, 4, 4, 4, 4}.AsReadOnly(), // 04:04:04:04:04:04.
                        TargetProtocolAddress = newbyte[] {11, 22, 33, 44}.AsReadOnly(), // 11.22.33.44.
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build a VLanTaggedFrame over Ethernet with payload packet.///</summary>privatestatic Packet BuildVLanTaggedFramePacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            VLanTaggedFrameLayer vLanTaggedFrameLayer =
                new VLanTaggedFrameLayer
                    {
                        PriorityCodePoint = ClassOfService.Background,
                        CanonicalFormatIndicator = false,
                        VLanIdentifier = 50,
                        EtherType = EthernetType.IpV4,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, vLanTaggedFrameLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an IPv4 over Ethernet with payload packet.///</summary>privatestatic Packet BuildIpV4Packet()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None,
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = IpV4Protocol.Udp,
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an ICMP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildIcmpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            IcmpEchoLayer icmpLayer =
                new IcmpEchoLayer
                    {
                        Checksum = null, // Will be filled automatically.
                        Identifier = 456,
                        SequenceNumber = 800,
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an IGMP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildIgmpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            IgmpQueryVersion1Layer igmpLayer =
                new IgmpQueryVersion1Layer
                    {
                        GroupAddress = new IpV4Address("1.2.3.4"),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, igmpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an IPv4 over GRE over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildGrePacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            GreLayer greLayer =
                new GreLayer
                    {
                        Version = GreVersion.Gre,
                        ProtocolType = EthernetType.None, // Will be filled automatically.
                        RecursionControl = 0,
                        FutureUseBits = 0,
                        ChecksumPresent = true,
                        Checksum = null, // Will be filled automatically.
                        Key = null,
                        SequenceNumber = 123,
                        AcknowledgmentSequenceNumber = null,
                        RoutingOffset = null,
                        Routing = null,
                        StrictSourceRoute = false,
                    };

            IpV4Layer innerIpV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("100.200.201.202"),
                        CurrentDestination = new IpV4Address("123.254.132.40"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = IpV4Protocol.Udp,
                        Ttl = 120,
                        TypeOfService = 0,
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, greLayer, innerIpV4Layer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an UDP over IPv4 over Ethernet with payload packet.///</summary>privatestatic Packet BuildUdpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            UdpLayer udpLayer =
                new UdpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 25,
                        Checksum = null, // Will be filled automatically.
                        CalculateChecksumValue = true,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an TCP over IPv4 over Ethernet with payload packet.///</summary>privatestatic Packet BuildTcpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            TcpLayer tcpLayer =
                new TcpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 25,
                        Checksum = null, // Will be filled automatically.
                        SequenceNumber = 100,
                        AcknowledgmentNumber = 50,
                        ControlBits = TcpControlBits.Acknowledgment,
                        Window = 100,
                        UrgentPointer = 0,
                        Options = TcpOptions.None,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }
        
        ///<summary>/// This function build a DNS over UDP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildDnsPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            UdpLayer udpLayer =
                new UdpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 53,
                        Checksum = null, // Will be filled automatically.
                        CalculateChecksumValue = true,
                    };

            DnsLayer dnsLayer =
                new DnsLayer
                    {
                        Id = 100,
                        IsResponse = false,
                        OpCode = DnsOpCode.Query,
                        IsAuthoritativeAnswer = false,
                        IsTruncated = false,
                        IsRecursionDesired = true,
                        IsRecursionAvailable = false,
                        FutureUse = false,
                        IsAuthenticData = false,
                        IsCheckingDisabled = false,
                        ResponseCode = DnsResponseCode.NoError,
                        Queries = new[]
                                      {
                                          new DnsQueryResourceRecord(new DnsDomainName("pcapdot.net"),
                                                                     DnsType.A,
                                                                     DnsClass.Internet),
                                      },
                        Answers = null,
                        Authorities = null,
                        Additionals = null,
                        DomainNameCompressionMode = DnsDomainNameCompressionMode.All,
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, dnsLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an HTTP over TCP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildHttpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            TcpLayer tcpLayer =
                new TcpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 80,
                        Checksum = null, // Will be filled automatically.
                        SequenceNumber = 100,
                        AcknowledgmentNumber = 50,
                        ControlBits = TcpControlBits.Acknowledgment,
                        Window = 100,
                        UrgentPointer = 0,
                        Options = TcpOptions.None,
                    };

            HttpRequestLayer httpLayer =
                new HttpRequestLayer
                    {
                        Version = HttpVersion.Version11,
                        Header = new HttpHeader(new HttpContentLengthField(11)),
                        Body = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                        Method = new HttpRequestMethod(HttpRequestKnownMethod.Get),
                        Uri = @"http://pcapdot.net/",
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, httpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build a DNS over UDP over IPv4 over GRE over IPv4 over IPv4 over VLAN Tagged Frame over VLAN Tagged Frame over Ethernet.///</summary>privatestatic Packet BuildComplexPacket()
        {
            return PacketBuilder.Build(
                DateTime.Now,
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    },
                new VLanTaggedFrameLayer
                    {
                        PriorityCodePoint = ClassOfService.ExcellentEffort,
                        CanonicalFormatIndicator = false,
                        EtherType = EthernetType.None, // Will be filled automatically.
                    },
                new VLanTaggedFrameLayer
                    {
                        PriorityCodePoint = ClassOfService.BestEffort,
                        CanonicalFormatIndicator = false,
                        EtherType = EthernetType.None, // Will be filled automatically.
                    },
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    },
                new IpV4Layer
                    {
                        Source = new IpV4Address("5.6.7.8"),
                        CurrentDestination = new IpV4Address("55.66.77.88"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 456,
                        Options = new IpV4Options(new IpV4OptionStrictSourceRouting(
                                                      new[]
                                                          {
                                                              new IpV4Address("100.200.100.200"),
                                                              new IpV4Address("150.250.150.250")
                                                          }, 1)),
                        Protocol = null, // Will be filled automatically.
                        Ttl = 200,
                        TypeOfService = 0,
                    },
                new GreLayer
                    {
                        Version = GreVersion.Gre,
                        ProtocolType = EthernetType.None, // Will be filled automatically.
                        RecursionControl = 0,
                        FutureUseBits = 0,
                        ChecksumPresent = true,
                        Checksum = null, // Will be filled automatically.
                        Key = 100,
                        SequenceNumber = 123,
                        AcknowledgmentSequenceNumber = null,
                        RoutingOffset = null,
                        Routing = new[]
                                      {
                                          new GreSourceRouteEntryIp(
                                              new[]
                                                  {
                                                      new IpV4Address("10.20.30.40"),
                                                      new IpV4Address("40.30.20.10")
                                                  }.AsReadOnly(), 1),
                                          new GreSourceRouteEntryIp(
                                              new[]
                                                  {
                                                      new IpV4Address("11.22.33.44"),
                                                      new IpV4Address("44.33.22.11")
                                                  }.AsReadOnly(), 0)
                                      }.Cast<GreSourceRouteEntry>().ToArray().AsReadOnly(),
                        StrictSourceRoute = false,
                    },
                new IpV4Layer
                    {
                        Source = new IpV4Address("51.52.53.54"),
                        CurrentDestination = new IpV4Address("61.62.63.64"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = new IpV4Options(
                            new IpV4OptionTimestampOnly(0, 1,
                                                        new IpV4TimeOfDay(new TimeSpan(1, 2, 3)),
                                                        new IpV4TimeOfDay(new TimeSpan(15, 55, 59))),
                            new IpV4OptionQuickStart(IpV4OptionQuickStartFunction.RateRequest, 10, 200, 300)),
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    },
                new UdpLayer
                    {
                        SourcePort = 53,
                        DestinationPort = 40101,
                        Checksum = null, // Will be filled automatically.
                        CalculateChecksumValue = true,
                    },
                new DnsLayer
                    {
                        Id = 10012,
                        IsResponse = true,
                        OpCode = DnsOpCode.Query,
                        IsAuthoritativeAnswer = true,
                        IsTruncated = false,
                        IsRecursionDesired = true,
                        IsRecursionAvailable = true,
                        FutureUse = false,
                        IsAuthenticData = true,
                        IsCheckingDisabled = false,
                        ResponseCode = DnsResponseCode.NoError,
                        Queries =
                            new[]
                                {
                                    new DnsQueryResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        DnsType.Any,
                                        DnsClass.Internet),
                                },
                        Answers =
                            new[]
                                {
                                    new DnsDataResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        DnsType.A,
                                        DnsClass.Internet
                                        , 50000,
                                        new DnsResourceDataIpV4(new IpV4Address("10.20.30.44"))),
                                    new DnsDataResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        DnsType.Txt,
                                        DnsClass.Internet,
                                        50000,
                                        new DnsResourceDataText(new[] {new DataSegment(Encoding.ASCII.GetBytes("Pcap.Net"))}.AsReadOnly()))
                                },
                        Authorities =
                            new[]
                                {
                                    new DnsDataResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        DnsType.MailExchange,
                                        DnsClass.Internet,
                                        100,
                                        new DnsResourceDataMailExchange(100, new DnsDomainName("pcapdot.net")))
                                },
                        Additionals =
                            new[]
                                {
                                    new DnsOptResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        50000,
                                        0,
                                        DnsOptVersion.Version0,
                                        DnsOptFlags.DnsSecOk,
                                        new DnsResourceDataOptions(
                                            new DnsOptions(
                                                new DnsOptionUpdateLease(100),
                                                new DnsOptionLongLivedQuery(1,
                                                                            DnsLongLivedQueryOpCode.Refresh,
                                                                            DnsLongLivedQueryErrorCode.NoError,
                                                                            10, 20))))
                                },
                        DomainNameCompressionMode = DnsDomainNameCompressionMode.All,
                    });
        }
    }
}

Sending packets using Send Buffer

While SendPacket() offers a simple and immediate way to send a single packet, send buffers provides an advanced, powerful and optimized mechanism to send a collection of packets. A send buffer is a container for a variable number of packets that will be sent to the network. It has a size, that represents the maximum amount of bytes it can store.

A send buffer is created calling the PacketSendBuffer constructor, specifying the size of the new send buffer.

Once the send buffer is created, Enqueue() can be used to add a packet to the send buffer. This function takes a packet with data and timestamp.

To transmit a send buffer, Pcap.Net provides the Transmit() method. Note the second parameter: if true, the send will be synchronized, i.e. the relative timestamps of the packets will be respected. This operation requires a remarkable amount of CPU, because the synchronization takes place in the kernel driver using "busy wait" loops. Although this operation is quite CPU intensive, it often results in very high precision packet transmissions (often around few microseconds or less).

Note that transmitting a send buffer with Transmit() is much more efficient than performing a series of SendPacket(), because the send buffer is buffered at kernel level drastically decreasing the number of context switches.

When a send buffer is no longer needed, it shoudl be disposed by calling Dispose() that frees all the buffers associated with the send buffer.

The next program shows how to use send buffers. It opens a capture file, then it moves the packets from the file to a properly allocated send buffer. At this point it transmits the buffer, synchronizing it if requested by the user.

Note that the link-layer of the dumpfile is compared with the one of the interface that will send the packets using DataLink, and a warning is printed if they are different -- it is important that the capture-file link-layer be the same as the adapter's link layer for otherwise the transmission is pointless.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using PcapDotNet.Core;
using PcapDotNet.Packets;

namespace SendingPacketsUsingSendBuffer
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Send anonymous statistics about the usage of Pcap.Net
            PcapDotNet.Analysis.PcapDotNetAnalysis.OptIn = true;

            // Check the validity of the command lineif (args.Length == 0 || args.Length > 2)
            {
                Usage();
                return;
            }

            // Retrieve the device list from the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the listfor (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedOutputDevice = allDevices[deviceIndex - 1];

            // Retrieve the length of the capture filelong capLength = new FileInfo(args[0]).Length;

            // Chek if the timestamps must be respectedbool isSync = (args.Length == 2 && args[1][0] == 's');

            // Open the capture file
            OfflinePacketDevice selectedInputDevice = new OfflinePacketDevice(args[0]);

            using (PacketCommunicator inputCommunicator =
                selectedInputDevice.Open(65536, // portion of the packet to capture// 65536 guarantees that the whole packet will be captured on all the link layers
                                         PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                         1000)) // read timeout
            {
                using (PacketCommunicator outputCommunicator =
                    selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    // Check the MAC typeif (inputCommunicator.DataLink != outputCommunicator.DataLink)
                    {
                        Console.WriteLine(
                            "Warning: the datalink of the capture differs from the one of the selected interface.");
                        Console.WriteLine("Press a key to continue, or CTRL+C to stop.");
                        Console.ReadKey();
                    }

                    // Allocate a send bufferusing (PacketSendBuffer sendBuffer = new PacketSendBuffer((uint)capLength))
                    {
                        // Fill the buffer with the packets from the fileint numPackets = 0;
                        Packet packet;
                        while (inputCommunicator.ReceivePacket(out packet) == PacketCommunicatorReceiveResult.Ok)
                        {
                            sendBuffer.Enqueue(packet);
                            ++numPackets;
                        }

                        // Transmit the queue
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();
                        long startTimeMs = stopwatch.ElapsedMilliseconds;
                        Console.WriteLine("Start Time: " + startTimeMs);
                        outputCommunicator.Transmit(sendBuffer, isSync);
                        long endTimeMs = stopwatch.ElapsedMilliseconds;
                        Console.WriteLine("End Time: " + endTimeMs);
                        long elapsedTimeMs = endTimeMs - startTimeMs;
                        Console.WriteLine("Elapsed Time: " + elapsedTimeMs);
                        double averagePacketsPerSecond = elapsedTimeMs == 0 ? double.MaxValue : (double)numPackets / elapsedTimeMs * 1000;

                        Console.WriteLine("Elapsed time: " + elapsedTimeMs + " ms");
                        Console.WriteLine("Total packets generated = " + numPackets);
                        Console.WriteLine("Average packets per second = " + averagePacketsPerSecond);
                        Console.WriteLine();
                    }
                }
            }
        }

        privatestaticvoid Usage()
        {
            Console.WriteLine("Sends a libpcap/tcpdump capture file to the net.");
            Console.WriteLine("Usage:");
            Console.WriteLine("\t" + Environment.GetCommandLineArgs()[0] + " <filename> [s]");
            Console.WriteLine();
            Console.WriteLine("Parameters:");
            Console.WriteLine("\tfilename: the name of the dump file that will be sent to the network");
            Console.WriteLine(
                "\ts: if present, forces the packets to be sent synchronously, i.e. respecting the timestamps in the dump file. This option will work only under Windows NTx");
        }
    }
}

<<< PreviousNext >>>

Updated Wiki: Pcap.Net Tutorial - Sending Packets

$
0
0

Sending Packets

Although the name Pcap.Net indicates clearly that the purpose of the library is packet capture, other useful features for raw networking are provided. Among them, the user can find a complete set of functions to send packets.

Note that the original libpcap library at the moment doesn't provide any way to send packets, therefore all the functions shown here are Pcap.Net extensions based on WinPcap extensions and will not work under Unix.

Sending a single packet with SendPacket()

The simplest way to send a packet is shown in the following code snippet. After opening an adapter, SendPacket() is called to send a hand-crafted packet. SendPacket() takes as argument the packet containing the data to send. Notice that the packet is sent to the net as is, without any manipulation. This means that the application has to create the correct protocol headers in order to send something meaningful.

This code uses SendPacket() to send 100 Ping (ICMP Echo) packets to different IPv4 destinations, with different IPv4 IDs, different ICMP Sequence Numbers and different ICMP Identifiers. This is done by creating a PacketBuilder instance with Ethernet, IPv4 and ICMP Echo layers, and by changing the layers' properties' values for each packet.
In addition, the code uses SendPacket() to send various packets. The creation of these packets is in the different Build...Packet() methods, and this can give you an overlook of the different packets you can create using Pcap.Net.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PcapDotNet.Base;
using PcapDotNet.Core;
using PcapDotNet.Packets;
using PcapDotNet.Packets.Arp;
using PcapDotNet.Packets.Dns;
using PcapDotNet.Packets.Ethernet;
using PcapDotNet.Packets.Gre;
using PcapDotNet.Packets.Http;
using PcapDotNet.Packets.Icmp;
using PcapDotNet.Packets.Igmp;
using PcapDotNet.Packets.IpV4;
using PcapDotNet.Packets.Transport;

namespace SendingASinglePacketWithSendPacket
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Retrieve the device list from the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the listfor (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[deviceIndex - 1];

            // Open the output deviceusing (PacketCommunicator communicator = selectedDevice.Open(100, // name of the device
                                                                         PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                                                         1000)) // read timeout
            {
                // Supposing to be on ethernet, set mac source to 01:01:01:01:01:01
                MacAddress source = new MacAddress("01:01:01:01:01:01");

                // set mac destination to 02:02:02:02:02:02
                MacAddress destination = new MacAddress("02:02:02:02:02:02");

                // Create the packets layers// Ethernet Layer
                EthernetLayer ethernetLayer = new EthernetLayer
                                                  {
                                                      Source = source,
                                                      Destination = destination
                                                  };

                // IPv4 Layer
                IpV4Layer ipV4Layer = new IpV4Layer
                                          {
                                              Source = new IpV4Address("1.2.3.4"),
                                              Ttl = 128,
                                              // The rest of the important parameters will be set for each packet
                                          };

                // ICMP Layer
                IcmpEchoLayer icmpLayer = new IcmpEchoLayer();

                // Create the builder that will build our packets
                PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);

                // Send 100 Pings to different destination with different parametersfor (int i = 0; i != 100; ++i)
                {
                    // Set IPv4 parameters
                    ipV4Layer.CurrentDestination = new IpV4Address("2.3.4." + i);
                    ipV4Layer.Identification = (ushort)i;

                    // Set ICMP parameters
                    icmpLayer.SequenceNumber = (ushort)i;
                    icmpLayer.Identifier = (ushort)i;

                    // Build the packet
                    Packet packet = builder.Build(DateTime.Now);

                    // Send down the packet
                    communicator.SendPacket(packet);
                }

                communicator.SendPacket(BuildEthernetPacket());
                communicator.SendPacket(BuildArpPacket());
                communicator.SendPacket(BuildVLanTaggedFramePacket());
                communicator.SendPacket(BuildIpV4Packet());
                communicator.SendPacket(BuildIcmpPacket());
                communicator.SendPacket(BuildIgmpPacket());
                communicator.SendPacket(BuildGrePacket());
                communicator.SendPacket(BuildUdpPacket());
                communicator.SendPacket(BuildTcpPacket());
                communicator.SendPacket(BuildDnsPacket());
                communicator.SendPacket(BuildHttpPacket());
                communicator.SendPacket(BuildComplexPacket());
            }
        }

        ///<summary>/// This function build an Ethernet with payload packet.///</summary>privatestatic Packet BuildEthernetPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.IpV4,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an ARP over Ethernet packet.///</summary>privatestatic Packet BuildArpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            ArpLayer arpLayer =
                new ArpLayer
                    {
                        ProtocolType = EthernetType.IpV4,
                        Operation = ArpOperation.Request,
                        SenderHardwareAddress = newbyte[] {3, 3, 3, 3, 3, 3}.AsReadOnly(), // 03:03:03:03:03:03.
                        SenderProtocolAddress = newbyte[] {1, 2, 3, 4}.AsReadOnly(), // 1.2.3.4.
                        TargetHardwareAddress = newbyte[] {4, 4, 4, 4, 4, 4}.AsReadOnly(), // 04:04:04:04:04:04.
                        TargetProtocolAddress = newbyte[] {11, 22, 33, 44}.AsReadOnly(), // 11.22.33.44.
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build a VLanTaggedFrame over Ethernet with payload packet.///</summary>privatestatic Packet BuildVLanTaggedFramePacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            VLanTaggedFrameLayer vLanTaggedFrameLayer =
                new VLanTaggedFrameLayer
                    {
                        PriorityCodePoint = ClassOfService.Background,
                        CanonicalFormatIndicator = false,
                        VLanIdentifier = 50,
                        EtherType = EthernetType.IpV4,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, vLanTaggedFrameLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an IPv4 over Ethernet with payload packet.///</summary>privatestatic Packet BuildIpV4Packet()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None,
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = IpV4Protocol.Udp,
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an ICMP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildIcmpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            IcmpEchoLayer icmpLayer =
                new IcmpEchoLayer
                    {
                        Checksum = null, // Will be filled automatically.
                        Identifier = 456,
                        SequenceNumber = 800,
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an IGMP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildIgmpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            IgmpQueryVersion1Layer igmpLayer =
                new IgmpQueryVersion1Layer
                    {
                        GroupAddress = new IpV4Address("1.2.3.4"),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, igmpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an IPv4 over GRE over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildGrePacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            GreLayer greLayer =
                new GreLayer
                    {
                        Version = GreVersion.Gre,
                        ProtocolType = EthernetType.None, // Will be filled automatically.
                        RecursionControl = 0,
                        FutureUseBits = 0,
                        ChecksumPresent = true,
                        Checksum = null, // Will be filled automatically.
                        Key = null,
                        SequenceNumber = 123,
                        AcknowledgmentSequenceNumber = null,
                        RoutingOffset = null,
                        Routing = null,
                        StrictSourceRoute = false,
                    };

            IpV4Layer innerIpV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("100.200.201.202"),
                        CurrentDestination = new IpV4Address("123.254.132.40"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = IpV4Protocol.Udp,
                        Ttl = 120,
                        TypeOfService = 0,
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, greLayer, innerIpV4Layer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an UDP over IPv4 over Ethernet with payload packet.///</summary>privatestatic Packet BuildUdpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            UdpLayer udpLayer =
                new UdpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 25,
                        Checksum = null, // Will be filled automatically.
                        CalculateChecksumValue = true,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an TCP over IPv4 over Ethernet with payload packet.///</summary>privatestatic Packet BuildTcpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            TcpLayer tcpLayer =
                new TcpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 25,
                        Checksum = null, // Will be filled automatically.
                        SequenceNumber = 100,
                        AcknowledgmentNumber = 50,
                        ControlBits = TcpControlBits.Acknowledgment,
                        Window = 100,
                        UrgentPointer = 0,
                        Options = TcpOptions.None,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }
        
        ///<summary>/// This function build a DNS over UDP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildDnsPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            UdpLayer udpLayer =
                new UdpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 53,
                        Checksum = null, // Will be filled automatically.
                        CalculateChecksumValue = true,
                    };

            DnsLayer dnsLayer =
                new DnsLayer
                    {
                        Id = 100,
                        IsResponse = false,
                        OpCode = DnsOpCode.Query,
                        IsAuthoritativeAnswer = false,
                        IsTruncated = false,
                        IsRecursionDesired = true,
                        IsRecursionAvailable = false,
                        FutureUse = false,
                        IsAuthenticData = false,
                        IsCheckingDisabled = false,
                        ResponseCode = DnsResponseCode.NoError,
                        Queries = new[]
                                      {
                                          new DnsQueryResourceRecord(new DnsDomainName("pcapdot.net"),
                                                                     DnsType.A,
                                                                     DnsClass.Internet),
                                      },
                        Answers = null,
                        Authorities = null,
                        Additionals = null,
                        DomainNameCompressionMode = DnsDomainNameCompressionMode.All,
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, dnsLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an HTTP over TCP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildHttpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            TcpLayer tcpLayer =
                new TcpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 80,
                        Checksum = null, // Will be filled automatically.
                        SequenceNumber = 100,
                        AcknowledgmentNumber = 50,
                        ControlBits = TcpControlBits.Acknowledgment,
                        Window = 100,
                        UrgentPointer = 0,
                        Options = TcpOptions.None,
                    };

            HttpRequestLayer httpLayer =
                new HttpRequestLayer
                    {
                        Version = HttpVersion.Version11,
                        Header = new HttpHeader(new HttpContentLengthField(11)),
                        Body = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                        Method = new HttpRequestMethod(HttpRequestKnownMethod.Get),
                        Uri = @"http://pcapdot.net/",
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, httpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build a DNS over UDP over IPv4 over GRE over IPv4 over IPv4 over VLAN Tagged Frame over VLAN Tagged Frame over Ethernet.///</summary>privatestatic Packet BuildComplexPacket()
        {
            return PacketBuilder.Build(
                DateTime.Now,
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    },
                new VLanTaggedFrameLayer
                    {
                        PriorityCodePoint = ClassOfService.ExcellentEffort,
                        CanonicalFormatIndicator = false,
                        EtherType = EthernetType.None, // Will be filled automatically.
                    },
                new VLanTaggedFrameLayer
                    {
                        PriorityCodePoint = ClassOfService.BestEffort,
                        CanonicalFormatIndicator = false,
                        EtherType = EthernetType.None, // Will be filled automatically.
                    },
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    },
                new IpV4Layer
                    {
                        Source = new IpV4Address("5.6.7.8"),
                        CurrentDestination = new IpV4Address("55.66.77.88"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 456,
                        Options = new IpV4Options(new IpV4OptionStrictSourceRouting(
                                                      new[]
                                                          {
                                                              new IpV4Address("100.200.100.200"),
                                                              new IpV4Address("150.250.150.250")
                                                          }, 1)),
                        Protocol = null, // Will be filled automatically.
                        Ttl = 200,
                        TypeOfService = 0,
                    },
                new GreLayer
                    {
                        Version = GreVersion.Gre,
                        ProtocolType = EthernetType.None, // Will be filled automatically.
                        RecursionControl = 0,
                        FutureUseBits = 0,
                        ChecksumPresent = true,
                        Checksum = null, // Will be filled automatically.
                        Key = 100,
                        SequenceNumber = 123,
                        AcknowledgmentSequenceNumber = null,
                        RoutingOffset = null,
                        Routing = new[]
                                      {
                                          new GreSourceRouteEntryIp(
                                              new[]
                                                  {
                                                      new IpV4Address("10.20.30.40"),
                                                      new IpV4Address("40.30.20.10")
                                                  }.AsReadOnly(), 1),
                                          new GreSourceRouteEntryIp(
                                              new[]
                                                  {
                                                      new IpV4Address("11.22.33.44"),
                                                      new IpV4Address("44.33.22.11")
                                                  }.AsReadOnly(), 0)
                                      }.Cast<GreSourceRouteEntry>().ToArray().AsReadOnly(),
                        StrictSourceRoute = false,
                    },
                new IpV4Layer
                    {
                        Source = new IpV4Address("51.52.53.54"),
                        CurrentDestination = new IpV4Address("61.62.63.64"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = new IpV4Options(
                            new IpV4OptionTimestampOnly(0, 1,
                                                        new IpV4TimeOfDay(new TimeSpan(1, 2, 3)),
                                                        new IpV4TimeOfDay(new TimeSpan(15, 55, 59))),
                            new IpV4OptionQuickStart(IpV4OptionQuickStartFunction.RateRequest, 10, 200, 300)),
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    },
                new UdpLayer
                    {
                        SourcePort = 53,
                        DestinationPort = 40101,
                        Checksum = null, // Will be filled automatically.
                        CalculateChecksumValue = true,
                    },
                new DnsLayer
                    {
                        Id = 10012,
                        IsResponse = true,
                        OpCode = DnsOpCode.Query,
                        IsAuthoritativeAnswer = true,
                        IsTruncated = false,
                        IsRecursionDesired = true,
                        IsRecursionAvailable = true,
                        FutureUse = false,
                        IsAuthenticData = true,
                        IsCheckingDisabled = false,
                        ResponseCode = DnsResponseCode.NoError,
                        Queries =
                            new[]
                                {
                                    new DnsQueryResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        DnsType.Any,
                                        DnsClass.Internet),
                                },
                        Answers =
                            new[]
                                {
                                    new DnsDataResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        DnsType.A,
                                        DnsClass.Internet
                                        , 50000,
                                        new DnsResourceDataIpV4(new IpV4Address("10.20.30.44"))),
                                    new DnsDataResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        DnsType.Txt,
                                        DnsClass.Internet,
                                        50000,
                                        new DnsResourceDataText(new[] {new DataSegment(Encoding.ASCII.GetBytes("Pcap.Net"))}.AsReadOnly()))
                                },
                        Authorities =
                            new[]
                                {
                                    new DnsDataResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        DnsType.MailExchange,
                                        DnsClass.Internet,
                                        100,
                                        new DnsResourceDataMailExchange(100, new DnsDomainName("pcapdot.net")))
                                },
                        Additionals =
                            new[]
                                {
                                    new DnsOptResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        50000,
                                        0,
                                        DnsOptVersion.Version0,
                                        DnsOptFlags.DnsSecOk,
                                        new DnsResourceDataOptions(
                                            new DnsOptions(
                                                new DnsOptionUpdateLease(100),
                                                new DnsOptionLongLivedQuery(1,
                                                                            DnsLongLivedQueryOpCode.Refresh,
                                                                            DnsLongLivedQueryErrorCode.NoError,
                                                                            10, 20))))
                                },
                        DomainNameCompressionMode = DnsDomainNameCompressionMode.All,
                    });
        }
    }
}

Sending packets using Send Buffer

While SendPacket() offers a simple and immediate way to send a single packet, send buffers provides an advanced, powerful and optimized mechanism to send a collection of packets. A send buffer is a container for a variable number of packets that will be sent to the network. It has a size, that represents the maximum amount of bytes it can store.

A send buffer is created calling the PacketSendBuffer constructor, specifying the size of the new send buffer.

Once the send buffer is created, Enqueue() can be used to add a packet to the send buffer. This function takes a packet with data and timestamp.

To transmit a send buffer, Pcap.Net provides the Transmit() method. Note the second parameter: if true, the send will be synchronized, i.e. the relative timestamps of the packets will be respected. This operation requires a remarkable amount of CPU, because the synchronization takes place in the kernel driver using "busy wait" loops. Although this operation is quite CPU intensive, it often results in very high precision packet transmissions (often around few microseconds or less).

Note that transmitting a send buffer with Transmit() is much more efficient than performing a series of SendPacket(), because the send buffer is buffered at kernel level drastically decreasing the number of context switches.

When a send buffer is no longer needed, it shoudl be disposed by calling Dispose() that frees all the buffers associated with the send buffer.

The next program shows how to use send buffers. It opens a capture file, then it moves the packets from the file to a properly allocated send buffer. At this point it transmits the buffer, synchronizing it if requested by the user.

Note that the link-layer of the dumpfile is compared with the one of the interface that will send the packets using DataLink, and a warning is printed if they are different -- it is important that the capture-file link-layer be the same as the adapter's link layer for otherwise the transmission is pointless.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using PcapDotNet.Core;
using PcapDotNet.Packets;

namespace SendingPacketsUsingSendBuffer
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Send anonymous statistics about the usage of Pcap.Net
            PcapDotNet.Analysis.PcapDotNetAnalysis.OptIn = true;

            // Check the validity of the command lineif (args.Length == 0 || args.Length > 2)
            {
                Usage();
                return;
            }

            // Retrieve the device list from the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the listfor (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedOutputDevice = allDevices[deviceIndex - 1];

            // Retrieve the length of the capture filelong capLength = new FileInfo(args[0]).Length;

            // Chek if the timestamps must be respectedbool isSync = (args.Length == 2 && args[1][0] == 's');

            // Open the capture file
            OfflinePacketDevice selectedInputDevice = new OfflinePacketDevice(args[0]);

            using (PacketCommunicator inputCommunicator =
                selectedInputDevice.Open(65536, // portion of the packet to capture// 65536 guarantees that the whole packet will be captured on all the link layers
                                         PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                         1000)) // read timeout
            {
                using (PacketCommunicator outputCommunicator =
                    selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    // Check the MAC typeif (inputCommunicator.DataLink != outputCommunicator.DataLink)
                    {
                        Console.WriteLine(
                            "Warning: the datalink of the capture differs from the one of the selected interface.");
                        Console.WriteLine("Press a key to continue, or CTRL+C to stop.");
                        Console.ReadKey();
                    }

                    // Allocate a send bufferusing (PacketSendBuffer sendBuffer = new PacketSendBuffer((uint)capLength))
                    {
                        // Fill the buffer with the packets from the fileint numPackets = 0;
                        Packet packet;
                        while (inputCommunicator.ReceivePacket(out packet) == PacketCommunicatorReceiveResult.Ok)
                        {
                            sendBuffer.Enqueue(packet);
                            ++numPackets;
                        }

                        // Transmit the queue
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();
                        long startTimeMs = stopwatch.ElapsedMilliseconds;
                        Console.WriteLine("Start Time: " + startTimeMs);
                        outputCommunicator.Transmit(sendBuffer, isSync);
                        long endTimeMs = stopwatch.ElapsedMilliseconds;
                        Console.WriteLine("End Time: " + endTimeMs);
                        long elapsedTimeMs = endTimeMs - startTimeMs;
                        Console.WriteLine("Elapsed Time: " + elapsedTimeMs);
                        double averagePacketsPerSecond = elapsedTimeMs == 0 ? double.MaxValue : (double)numPackets / elapsedTimeMs * 1000;

                        Console.WriteLine("Elapsed time: " + elapsedTimeMs + " ms");
                        Console.WriteLine("Total packets generated = " + numPackets);
                        Console.WriteLine("Average packets per second = " + averagePacketsPerSecond);
                        Console.WriteLine();
                    }
                }
            }
        }

        privatestaticvoid Usage()
        {
            Console.WriteLine("Sends a libpcap/tcpdump capture file to the net.");
            Console.WriteLine("Usage:");
            Console.WriteLine("\t" + Environment.GetCommandLineArgs()[0] + " <filename> [s]");
            Console.WriteLine();
            Console.WriteLine("Parameters:");
            Console.WriteLine("\tfilename: the name of the dump file that will be sent to the network");
            Console.WriteLine(
                "\ts: if present, forces the packets to be sent synchronously, i.e. respecting the timestamps in the dump file. This option will work only under Windows NTx");
        }
    }
}

<<< PreviousNext >>>

Updated Wiki: Pcap.Net Tutorial - Sending Packets

$
0
0

Sending Packets

Although the name Pcap.Net indicates clearly that the purpose of the library is packet capture, other useful features for raw networking are provided. Among them, the user can find a complete set of functions to send packets.

Note that the original libpcap library at the moment doesn't provide any way to send packets, therefore all the functions shown here are Pcap.Net extensions based on WinPcap extensions and will not work under Unix.

Sending a single packet with SendPacket()

The simplest way to send a packet is shown in the following code snippet. After opening an adapter, SendPacket() is called to send a hand-crafted packet. SendPacket() takes as argument the packet containing the data to send. Notice that the packet is sent to the net as is, without any manipulation. This means that the application has to create the correct protocol headers in order to send something meaningful.

This code uses SendPacket() to send 100 Ping (ICMP Echo) packets to different IPv4 destinations, with different IPv4 IDs, different ICMP Sequence Numbers and different ICMP Identifiers. This is done by creating a PacketBuilder instance with Ethernet, IPv4 and ICMP Echo layers, and by changing the layers' properties' values for each packet.
In addition, the code uses SendPacket() to send various packets. The creation of these packets is in the different Build...Packet() methods, and this can give you an overlook of the different packets you can create using Pcap.Net.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PcapDotNet.Base;
using PcapDotNet.Core;
using PcapDotNet.Packets;
using PcapDotNet.Packets.Arp;
using PcapDotNet.Packets.Dns;
using PcapDotNet.Packets.Ethernet;
using PcapDotNet.Packets.Gre;
using PcapDotNet.Packets.Http;
using PcapDotNet.Packets.Icmp;
using PcapDotNet.Packets.Igmp;
using PcapDotNet.Packets.IpV4;
using PcapDotNet.Packets.Transport;

namespace SendingASinglePacketWithSendPacket
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Retrieve the device list from the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the listfor (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[deviceIndex - 1];

            // Open the output deviceusing (PacketCommunicator communicator = selectedDevice.Open(100, // name of the device
                                                                         PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                                                         1000)) // read timeout
            {
                // Supposing to be on ethernet, set mac source to 01:01:01:01:01:01
                MacAddress source = new MacAddress("01:01:01:01:01:01");

                // set mac destination to 02:02:02:02:02:02
                MacAddress destination = new MacAddress("02:02:02:02:02:02");

                // Create the packets layers// Ethernet Layer
                EthernetLayer ethernetLayer = new EthernetLayer
                                                  {
                                                      Source = source,
                                                      Destination = destination
                                                  };

                // IPv4 Layer
                IpV4Layer ipV4Layer = new IpV4Layer
                                          {
                                              Source = new IpV4Address("1.2.3.4"),
                                              Ttl = 128,
                                              // The rest of the important parameters will be set for each packet
                                          };

                // ICMP Layer
                IcmpEchoLayer icmpLayer = new IcmpEchoLayer();

                // Create the builder that will build our packets
                PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);

                // Send 100 Pings to different destination with different parametersfor (int i = 0; i != 100; ++i)
                {
                    // Set IPv4 parameters
                    ipV4Layer.CurrentDestination = new IpV4Address("2.3.4." + i);
                    ipV4Layer.Identification = (ushort)i;

                    // Set ICMP parameters
                    icmpLayer.SequenceNumber = (ushort)i;
                    icmpLayer.Identifier = (ushort)i;

                    // Build the packet
                    Packet packet = builder.Build(DateTime.Now);

                    // Send down the packet
                    communicator.SendPacket(packet);
                }

                communicator.SendPacket(BuildEthernetPacket());
                communicator.SendPacket(BuildArpPacket());
                communicator.SendPacket(BuildVLanTaggedFramePacket());
                communicator.SendPacket(BuildIpV4Packet());
                communicator.SendPacket(BuildIcmpPacket());
                communicator.SendPacket(BuildIgmpPacket());
                communicator.SendPacket(BuildGrePacket());
                communicator.SendPacket(BuildUdpPacket());
                communicator.SendPacket(BuildTcpPacket());
                communicator.SendPacket(BuildDnsPacket());
                communicator.SendPacket(BuildHttpPacket());
                communicator.SendPacket(BuildComplexPacket());
            }
        }

        ///<summary>/// This function build an Ethernet with payload packet.///</summary>privatestatic Packet BuildEthernetPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.IpV4,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an ARP over Ethernet packet.///</summary>privatestatic Packet BuildArpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            ArpLayer arpLayer =
                new ArpLayer
                    {
                        ProtocolType = EthernetType.IpV4,
                        Operation = ArpOperation.Request,
                        SenderHardwareAddress = newbyte[] {3, 3, 3, 3, 3, 3}.AsReadOnly(), // 03:03:03:03:03:03.
                        SenderProtocolAddress = newbyte[] {1, 2, 3, 4}.AsReadOnly(), // 1.2.3.4.
                        TargetHardwareAddress = newbyte[] {4, 4, 4, 4, 4, 4}.AsReadOnly(), // 04:04:04:04:04:04.
                        TargetProtocolAddress = newbyte[] {11, 22, 33, 44}.AsReadOnly(), // 11.22.33.44.
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build a VLanTaggedFrame over Ethernet with payload packet.///</summary>privatestatic Packet BuildVLanTaggedFramePacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            VLanTaggedFrameLayer vLanTaggedFrameLayer =
                new VLanTaggedFrameLayer
                    {
                        PriorityCodePoint = ClassOfService.Background,
                        CanonicalFormatIndicator = false,
                        VLanIdentifier = 50,
                        EtherType = EthernetType.IpV4,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, vLanTaggedFrameLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an IPv4 over Ethernet with payload packet.///</summary>privatestatic Packet BuildIpV4Packet()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None,
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = IpV4Protocol.Udp,
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an ICMP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildIcmpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            IcmpEchoLayer icmpLayer =
                new IcmpEchoLayer
                    {
                        Checksum = null, // Will be filled automatically.
                        Identifier = 456,
                        SequenceNumber = 800,
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an IGMP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildIgmpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            IgmpQueryVersion1Layer igmpLayer =
                new IgmpQueryVersion1Layer
                    {
                        GroupAddress = new IpV4Address("1.2.3.4"),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, igmpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an IPv4 over GRE over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildGrePacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            GreLayer greLayer =
                new GreLayer
                    {
                        Version = GreVersion.Gre,
                        ProtocolType = EthernetType.None, // Will be filled automatically.
                        RecursionControl = 0,
                        FutureUseBits = 0,
                        ChecksumPresent = true,
                        Checksum = null, // Will be filled automatically.
                        Key = null,
                        SequenceNumber = 123,
                        AcknowledgmentSequenceNumber = null,
                        RoutingOffset = null,
                        Routing = null,
                        StrictSourceRoute = false,
                    };

            IpV4Layer innerIpV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("100.200.201.202"),
                        CurrentDestination = new IpV4Address("123.254.132.40"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = IpV4Protocol.Udp,
                        Ttl = 120,
                        TypeOfService = 0,
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, greLayer, innerIpV4Layer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an UDP over IPv4 over Ethernet with payload packet.///</summary>privatestatic Packet BuildUdpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            UdpLayer udpLayer =
                new UdpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 25,
                        Checksum = null, // Will be filled automatically.
                        CalculateChecksumValue = true,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an TCP over IPv4 over Ethernet with payload packet.///</summary>privatestatic Packet BuildTcpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            TcpLayer tcpLayer =
                new TcpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 25,
                        Checksum = null, // Will be filled automatically.
                        SequenceNumber = 100,
                        AcknowledgmentNumber = 50,
                        ControlBits = TcpControlBits.Acknowledgment,
                        Window = 100,
                        UrgentPointer = 0,
                        Options = TcpOptions.None,
                    };

            PayloadLayer payloadLayer =
                new PayloadLayer
                    {
                        Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, payloadLayer);

            return builder.Build(DateTime.Now);
        }
        
        ///<summary>/// This function build a DNS over UDP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildDnsPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            UdpLayer udpLayer =
                new UdpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 53,
                        Checksum = null, // Will be filled automatically.
                        CalculateChecksumValue = true,
                    };

            DnsLayer dnsLayer =
                new DnsLayer
                    {
                        Id = 100,
                        IsResponse = false,
                        OpCode = DnsOpCode.Query,
                        IsAuthoritativeAnswer = false,
                        IsTruncated = false,
                        IsRecursionDesired = true,
                        IsRecursionAvailable = false,
                        FutureUse = false,
                        IsAuthenticData = false,
                        IsCheckingDisabled = false,
                        ResponseCode = DnsResponseCode.NoError,
                        Queries = new[]
                                      {
                                          new DnsQueryResourceRecord(new DnsDomainName("pcapdot.net"),
                                                                     DnsType.A,
                                                                     DnsClass.Internet),
                                      },
                        Answers = null,
                        Authorities = null,
                        Additionals = null,
                        DomainNameCompressionMode = DnsDomainNameCompressionMode.All,
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, dnsLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build an HTTP over TCP over IPv4 over Ethernet packet.///</summary>privatestatic Packet BuildHttpPacket()
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    };

            TcpLayer tcpLayer =
                new TcpLayer
                    {
                        SourcePort = 4050,
                        DestinationPort = 80,
                        Checksum = null, // Will be filled automatically.
                        SequenceNumber = 100,
                        AcknowledgmentNumber = 50,
                        ControlBits = TcpControlBits.Acknowledgment,
                        Window = 100,
                        UrgentPointer = 0,
                        Options = TcpOptions.None,
                    };

            HttpRequestLayer httpLayer =
                new HttpRequestLayer
                    {
                        Version = HttpVersion.Version11,
                        Header = new HttpHeader(new HttpContentLengthField(11)),
                        Body = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                        Method = new HttpRequestMethod(HttpRequestKnownMethod.Get),
                        Uri = @"http://pcapdot.net/",
                    };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, tcpLayer, httpLayer);

            return builder.Build(DateTime.Now);
        }

        ///<summary>/// This function build a DNS over UDP over IPv4 over GRE over IPv4 over IPv4 over VLAN Tagged Frame over VLAN Tagged Frame over Ethernet.///</summary>privatestatic Packet BuildComplexPacket()
        {
            return PacketBuilder.Build(
                DateTime.Now,
                new EthernetLayer
                    {
                        Source = new MacAddress("01:01:01:01:01:01"),
                        Destination = new MacAddress("02:02:02:02:02:02"),
                        EtherType = EthernetType.None, // Will be filled automatically.
                    },
                new VLanTaggedFrameLayer
                    {
                        PriorityCodePoint = ClassOfService.ExcellentEffort,
                        CanonicalFormatIndicator = false,
                        EtherType = EthernetType.None, // Will be filled automatically.
                    },
                new VLanTaggedFrameLayer
                    {
                        PriorityCodePoint = ClassOfService.BestEffort,
                        CanonicalFormatIndicator = false,
                        EtherType = EthernetType.None, // Will be filled automatically.
                    },
                new IpV4Layer
                    {
                        Source = new IpV4Address("1.2.3.4"),
                        CurrentDestination = new IpV4Address("11.22.33.44"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = IpV4Options.None,
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    },
                new IpV4Layer
                    {
                        Source = new IpV4Address("5.6.7.8"),
                        CurrentDestination = new IpV4Address("55.66.77.88"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 456,
                        Options = new IpV4Options(new IpV4OptionStrictSourceRouting(
                                                      new[]
                                                          {
                                                              new IpV4Address("100.200.100.200"),
                                                              new IpV4Address("150.250.150.250")
                                                          }, 1)),
                        Protocol = null, // Will be filled automatically.
                        Ttl = 200,
                        TypeOfService = 0,
                    },
                new GreLayer
                    {
                        Version = GreVersion.Gre,
                        ProtocolType = EthernetType.None, // Will be filled automatically.
                        RecursionControl = 0,
                        FutureUseBits = 0,
                        ChecksumPresent = true,
                        Checksum = null, // Will be filled automatically.
                        Key = 100,
                        SequenceNumber = 123,
                        AcknowledgmentSequenceNumber = null,
                        RoutingOffset = null,
                        Routing = new[]
                                      {
                                          new GreSourceRouteEntryIp(
                                              new[]
                                                  {
                                                      new IpV4Address("10.20.30.40"),
                                                      new IpV4Address("40.30.20.10")
                                                  }.AsReadOnly(), 1),
                                          new GreSourceRouteEntryIp(
                                              new[]
                                                  {
                                                      new IpV4Address("11.22.33.44"),
                                                      new IpV4Address("44.33.22.11")
                                                  }.AsReadOnly(), 0)
                                      }.Cast<GreSourceRouteEntry>().ToArray().AsReadOnly(),
                        StrictSourceRoute = false,
                    },
                new IpV4Layer
                    {
                        Source = new IpV4Address("51.52.53.54"),
                        CurrentDestination = new IpV4Address("61.62.63.64"),
                        Fragmentation = IpV4Fragmentation.None,
                        HeaderChecksum = null, // Will be filled automatically.
                        Identification = 123,
                        Options = new IpV4Options(
                            new IpV4OptionTimestampOnly(0, 1,
                                                        new IpV4TimeOfDay(new TimeSpan(1, 2, 3)),
                                                        new IpV4TimeOfDay(new TimeSpan(15, 55, 59))),
                            new IpV4OptionQuickStart(IpV4OptionQuickStartFunction.RateRequest, 10, 200, 300)),
                        Protocol = null, // Will be filled automatically.
                        Ttl = 100,
                        TypeOfService = 0,
                    },
                new UdpLayer
                    {
                        SourcePort = 53,
                        DestinationPort = 40101,
                        Checksum = null, // Will be filled automatically.
                        CalculateChecksumValue = true,
                    },
                new DnsLayer
                    {
                        Id = 10012,
                        IsResponse = true,
                        OpCode = DnsOpCode.Query,
                        IsAuthoritativeAnswer = true,
                        IsTruncated = false,
                        IsRecursionDesired = true,
                        IsRecursionAvailable = true,
                        FutureUse = false,
                        IsAuthenticData = true,
                        IsCheckingDisabled = false,
                        ResponseCode = DnsResponseCode.NoError,
                        Queries =
                            new[]
                                {
                                    new DnsQueryResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        DnsType.Any,
                                        DnsClass.Internet),
                                },
                        Answers =
                            new[]
                                {
                                    new DnsDataResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        DnsType.A,
                                        DnsClass.Internet
                                        , 50000,
                                        new DnsResourceDataIpV4(new IpV4Address("10.20.30.44"))),
                                    new DnsDataResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        DnsType.Txt,
                                        DnsClass.Internet,
                                        50000,
                                        new DnsResourceDataText(new[] {new DataSegment(Encoding.ASCII.GetBytes("Pcap.Net"))}.AsReadOnly()))
                                },
                        Authorities =
                            new[]
                                {
                                    new DnsDataResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        DnsType.MailExchange,
                                        DnsClass.Internet,
                                        100,
                                        new DnsResourceDataMailExchange(100, new DnsDomainName("pcapdot.net")))
                                },
                        Additionals =
                            new[]
                                {
                                    new DnsOptResourceRecord(
                                        new DnsDomainName("pcapdot.net"),
                                        50000,
                                        0,
                                        DnsOptVersion.Version0,
                                        DnsOptFlags.DnsSecOk,
                                        new DnsResourceDataOptions(
                                            new DnsOptions(
                                                new DnsOptionUpdateLease(100),
                                                new DnsOptionLongLivedQuery(1,
                                                                            DnsLongLivedQueryOpCode.Refresh,
                                                                            DnsLongLivedQueryErrorCode.NoError,
                                                                            10, 20))))
                                },
                        DomainNameCompressionMode = DnsDomainNameCompressionMode.All,
                    });
        }
    }
}

Sending packets using Send Buffer

While SendPacket() offers a simple and immediate way to send a single packet, send buffers provides an advanced, powerful and optimized mechanism to send a collection of packets. A send buffer is a container for a variable number of packets that will be sent to the network. It has a size, that represents the maximum amount of bytes it can store.

A send buffer is created calling the PacketSendBuffer constructor, specifying the size of the new send buffer.

Once the send buffer is created, Enqueue() can be used to add a packet to the send buffer. This function takes a packet with data and timestamp.

To transmit a send buffer, Pcap.Net provides the Transmit() method. Note the second parameter: if true, the send will be synchronized, i.e. the relative timestamps of the packets will be respected. This operation requires a remarkable amount of CPU, because the synchronization takes place in the kernel driver using "busy wait" loops. Although this operation is quite CPU intensive, it often results in very high precision packet transmissions (often around few microseconds or less).

Note that transmitting a send buffer with Transmit() is much more efficient than performing a series of SendPacket(), because the send buffer is buffered at kernel level drastically decreasing the number of context switches.

When a send buffer is no longer needed, it shoudl be disposed by calling Dispose() that frees all the buffers associated with the send buffer.

The next program shows how to use send buffers. It opens a capture file, then it moves the packets from the file to a properly allocated send buffer. At this point it transmits the buffer, synchronizing it if requested by the user.

Note that the link-layer of the dumpfile is compared with the one of the interface that will send the packets using DataLink, and a warning is printed if they are different -- it is important that the capture-file link-layer be the same as the adapter's link layer for otherwise the transmission is pointless.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using PcapDotNet.Core;
using PcapDotNet.Packets;

namespace SendingPacketsUsingSendBuffer
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Check the validity of the command lineif (args.Length == 0 || args.Length > 2)
            {
                Usage();
                return;
            }

            // Retrieve the device list from the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the listfor (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedOutputDevice = allDevices[deviceIndex - 1];

            // Retrieve the length of the capture filelong capLength = new FileInfo(args[0]).Length;

            // Chek if the timestamps must be respectedbool isSync = (args.Length == 2 && args[1][0] == 's');

            // Open the capture file
            OfflinePacketDevice selectedInputDevice = new OfflinePacketDevice(args[0]);

            using (PacketCommunicator inputCommunicator =
                selectedInputDevice.Open(65536, // portion of the packet to capture// 65536 guarantees that the whole packet will be captured on all the link layers
                                         PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                         1000)) // read timeout
            {
                using (PacketCommunicator outputCommunicator =
                    selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000))
                {
                    // Check the MAC typeif (inputCommunicator.DataLink != outputCommunicator.DataLink)
                    {
                        Console.WriteLine(
                            "Warning: the datalink of the capture differs from the one of the selected interface.");
                        Console.WriteLine("Press a key to continue, or CTRL+C to stop.");
                        Console.ReadKey();
                    }

                    // Allocate a send bufferusing (PacketSendBuffer sendBuffer = new PacketSendBuffer((uint)capLength))
                    {
                        // Fill the buffer with the packets from the fileint numPackets = 0;
                        Packet packet;
                        while (inputCommunicator.ReceivePacket(out packet) == PacketCommunicatorReceiveResult.Ok)
                        {
                            sendBuffer.Enqueue(packet);
                            ++numPackets;
                        }

                        // Transmit the queue
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();
                        long startTimeMs = stopwatch.ElapsedMilliseconds;
                        Console.WriteLine("Start Time: " + startTimeMs);
                        outputCommunicator.Transmit(sendBuffer, isSync);
                        long endTimeMs = stopwatch.ElapsedMilliseconds;
                        Console.WriteLine("End Time: " + endTimeMs);
                        long elapsedTimeMs = endTimeMs - startTimeMs;
                        Console.WriteLine("Elapsed Time: " + elapsedTimeMs);
                        double averagePacketsPerSecond = elapsedTimeMs == 0 ? double.MaxValue : (double)numPackets / elapsedTimeMs * 1000;

                        Console.WriteLine("Elapsed time: " + elapsedTimeMs + " ms");
                        Console.WriteLine("Total packets generated = " + numPackets);
                        Console.WriteLine("Average packets per second = " + averagePacketsPerSecond);
                        Console.WriteLine();
                    }
                }
            }
        }

        privatestaticvoid Usage()
        {
            Console.WriteLine("Sends a libpcap/tcpdump capture file to the net.");
            Console.WriteLine("Usage:");
            Console.WriteLine("\t" + Environment.GetCommandLineArgs()[0] + " <filename> [s]");
            Console.WriteLine();
            Console.WriteLine("Parameters:");
            Console.WriteLine("\tfilename: the name of the dump file that will be sent to the network");
            Console.WriteLine(
                "\ts: if present, forces the packets to be sent synchronously, i.e. respecting the timestamps in the dump file. This option will work only under Windows NTx");
        }
    }
}

<<< PreviousNext >>>

Updated Wiki: Pcap.Net Tutorial - Gathering Statistics on the network traffic

$
0
0

Gathering Statistics on the network traffic

This lesson shows another advanced feature of Pcap.Net: the ability to collect statistics about network traffic. The statistical engine makes use of the kernel-level packet filter to efficiently classify the incoming packet. You can take a look at the NPF driver internals manual if you want to know more details.

In order to use this feature, the programmer must open an adapter and put it in statistical mode. This can be done with the Mode property. In particular, Mode.Statistics must be used as the mode value of this property.

With statistical mode, making an application that monitors the TCP traffic load is a matter of few lines of code. The following sample shows how to do it.

using System;
using System.Collections.Generic;
using PcapDotNet.Core;

namespace GatheringStatisticsOnTheNetworkTraffic
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Retrieve the device list from the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the listfor (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedOutputDevice = allDevices[deviceIndex - 1];

            // Open the output adapterusing (
                PacketCommunicator communicator = selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous,
                                                                            1000))
            {
                // Compile and set the filter
                communicator.SetFilter("tcp");

                // Put the interface in statstics mode
                communicator.Mode = PacketCommunicatorMode.Statistics;

                Console.WriteLine("TCP traffic summary:");

                // Start the main loop
                communicator.ReceiveStatistics(0, StatisticsHandler);
            }
        }

        privatestaticvoid StatisticsHandler(PacketSampleStatistics statistics)
        {
            // Current sample time
            DateTime currentTimestamp = statistics.Timestamp;

            // Previous sample time
            DateTime previousTimestamp = _lastTimestamp;

            // Set _lastTimestamp for the next iteration
            _lastTimestamp = currentTimestamp;

            // If there wasn't a previous sample than skip this iteration (it's the first iteration)if (previousTimestamp == DateTime.MinValue)
                return;

            // Calculate the delay from the last sampledouble delayInSeconds = (currentTimestamp - previousTimestamp).TotalSeconds;

            // Calculate bits per seconddouble bitsPerSecond = statistics.AcceptedBytes * 8 / delayInSeconds;

            // Calculate packets per seconddouble packetsPerSecond = statistics.AcceptedPackets / delayInSeconds;

            // Print timestamp and samples
            Console.WriteLine(statistics.Timestamp + " BPS: " + bitsPerSecond + " PPS: " + packetsPerSecond);
        }

        privatestatic DateTime _lastTimestamp;
    }
}

Before enabling statistical mode, the user has the option to set a filter that defines the subset of network traffic that will be monitored. See the paragraph on the WinPcap Filtering expression syntax for details. If no filter has been set, all of the traffic will be monitored.

Once
  • The filter is set
  • PacketCommunicator.Mode is set
  • Callback invocation is enabled with ReceiveStatistics()
The interface descriptor starts to work in statistical mode. Notice the third parameter (readTimeout) of Open(): it defines the interval among the statistical samples. The callback function receives the samples calculated by the driver every readTimeout milliseconds.

In the example, the adapter is opened with a timeout of 1000 ms. This means that StatisticsHandler() is called once per second. At this point a filter that keeps only tcp packets is compiled and set. Then the Mode property is set and ReceiveStatistics() is called. Note that there's a static data member, _lastTimestamp, which is used to store the previous timestamp in order to calculate the interval between two samples. StatisticsHandler()uses this interval to obtain the bits per second and the packets per second and then prints these values on the screen.

Note finally that this example is by far more efficient than a program that captures the packets in the traditional way and calculates statistics at user-level. Statistical mode requires the minumum amount of data copies and context switches and therefore the CPU is optimized. Moreover, a very small amount of memory is required.

<<< PreviousNext >>>

Updated Wiki: Pcap.Net Tutorial - Using LINQ

$
0
0

Using LINQ

The release of Pcap.Net 0.3.0 includes a new feature within a new extensions dll that contains extensions for the Pcap.Net core functionality.
The feature allows the user to receive packets using an IEnumerable<Packet> instance using an extension method for the PacketCommunicator that overloads ReceivePackets().

One important note regarding this overload is that it uses ReceiveSomePackets() internally in a loop. This means that if the user wants to receive N packets in the Enumerable, it doesn't mean that the method will read exactly N packets from the device. It might read more packets since ReceiveSomePackets() reads all the packets that arrive in the same buffer.
The reason for implementing this feature this way is that receiving each packet separately will have a performance hit and for most uses it doesn't matter that a few packets will be thrown after the Enumerable was filled with the requested number of packets.
If there is need for different way to receive packets as an Enumerable, write about it in the Discussions and I'll add more functionality.

In the following example, the user takes 100 packets that follow the BPF "ip and tcp" and selects using LINQ the timestamp and TCP options of the packets that have options.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using PcapDotNet.Core;
using PcapDotNet.Core.Extensions;
using PcapDotNet.Packets;

namespace UsingLinq
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Retrieve the device list from the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the listfor (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[deviceIndex - 1];

            // Open the deviceusing (PacketCommunicator communicator =
                selectedDevice.Open(65536,                                  // portion of the packet to capture// 65536 guarantees that the whole packet will be captured on all the link layers
                                    PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                    1000))                                  // read timeout
            {
                // Check the link layer. We support only Ethernet for simplicity.if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
                {
                    Console.WriteLine("This program works only on Ethernet networks.");
                    return;
                }

                // Compile and set the filter
                communicator.SetFilter("ip and tcp");

                Console.WriteLine("Listening on " + selectedDevice.Description + "...");

                // start the capturevar query = from packet in communicator.ReceivePackets(100)
                            where packet.Ethernet.IpV4.Tcp.Options.Count != 0
                            selectnew {packet.Timestamp, packet.Ethernet.IpV4.Tcp.Options};

                foreach (var options in query)
                    Console.WriteLine(options.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " options: " + options.Options);
            }
        }
    }
}

<<< Previous

Updated Wiki: Home

$
0
0
Welcome to Pcap.Net!
Pcap.Net is a .NET wrapper for WinPcap written in C++/CLI and C#.
It Features almost all WinPcap features and includes a packet interpretation framework.

Give Feedback!
Pcap.Net Features

.Net wrap for WinPcap

Including:
  • Getting the list of Live Devices on the local host.
  • Reading packets from Live Devices (Network Devices) and Offline Devices (Files) using the different WinPcap methods.
  • Receiving statistics on the entire capture.
  • Receiving statistics of packets instead of the full packets.
  • Using different sampling methods.
  • Applying Berkley Packet Filters.
  • Sending packets to Live Devices directly or using WinPcap's send queues.
  • Dumping packets to Pcap files.
  • Using Enumerables to receive packets (and LINQ).
Not including:
  • AirPcap features.
  • Remote Pcap features.

Packet interpretation
  • Ethernet + VLAN tagging (802.1Q)
  • ARP
  • IPv4
  • GRE
  • ICMP
  • IGMP
  • UDP
  • TCP
  • DNS
  • HTTP

Follow Pcap.Net on Google+Follow Pcap.Net on Google+

Support Pcap.Net

Support Pcap.Net by donation
Or just send some Bitcoins - 16hxsYCEahBEKcoCJZ7YVUGQNzLkLaGiLe

New Comment on "Using Pcap.Net in your programs"

$
0
0
I use visuel studio 2008 I can't run the application that contain PcapDotNet.Core , I 'd trying to add a reference but I did not found the files when can I find it? thanks

New Comment on "Pcap.Net Tutorial - Opening an adapter and capturing the packets"

$
0
0
sorry i have a question about the combination of the timeout of the Open function and the count of the ReceivePacket count parameter, for example what if the Open has 0 and the count is 0 too, or if is -1 that means that has to return inmediatly but the count is 19 so it has to wait or what?

Updated Wiki: Pcap.Net Tutorial - Handling offline dump files

$
0
0

Handling offline dump files

In this lession we are going to learn how to handle packet capture to a file (dump to file). Pcap.Net offers a wide range of functions to save the network traffic to a file and to read the content of dumps -- this lesson will teach how to use all of these functions.

The format for dump files is the libpcap one. This format contains the data of the captured packets in binary form and is a standard used by many network tools including WinDump, Ethereal and Snort.

Saving packets to a dump file

First of all, let's see how to write packets in libpcap format.

The following example captures the packets from the selected interface and saves them on a file whose name is provided by the user.

using System;
using System.Collections.Generic;
using PcapDotNet.Core;

namespace SavingPacketsToADumpFile
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Check command lineif (args.Length != 1)
            {
                Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " <filename>");
                return;
            }

            // Retrieve the device list on the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the listfor (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[deviceIndex - 1];

            // Open the deviceusing (PacketCommunicator communicator =
                selectedDevice.Open(65536, // portion of the packet to capture// 65536 guarantees that the whole packet will be captured on all the link layers
                                    PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                    1000)) // read timeout
            {
                // Open the dump fileusing (PacketDumpFile dumpFile = communicator.OpenDump(args[0]))
                {
                    Console.WriteLine("Listening on " + selectedDevice.Description + "... Press Ctrl+C to stop...");

                    // start the capture
                    communicator.ReceivePackets(0, dumpFile.Dump);
                }
            }
        }
    }
}

As you can see, the structure of the program is very similar to the ones we have seen in the previous lessons. The differences are:
  • A call to OpenDump() is issued once the interface is opened. This call opens a dump file and associates it with the interface.
  • The packets are written to this file by setting the callback to the dump file's Dump() method. A different approach would be to give a specially created method for as a callback or an anonymous delegate.
  • A different and very simple way to dump Packets into a file is by calling PacketDumpFile.Dump() static method.

Reading packets from a dump file

Now that we have a dump file available, we can try to read its content. The following code opens a libpcap dump file and displays every packet contained in the file. The file is opened with Open(), then the usual ReceivePackets() is used to sequence through the packets. As you can see, reading packets from an offline capture is nearly identical to receiving them from a physical interface.

using System;
using PcapDotNet.Core;
using PcapDotNet.Packets;

namespace ReadingPacketsFromADumpFile
{
    class Program
    {
        staticvoid Main(string[] args)
        {
            // Check command lineif (args.Length != 1)
            {
                Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " <filename>");
                return;
            }

            // Create the offline device
            OfflinePacketDevice selectedDevice = new OfflinePacketDevice(args[0]);

            // Open the capture fileusing (PacketCommunicator communicator =
                selectedDevice.Open(65536,                                  // portion of the packet to capture// 65536 guarantees that the whole packet will be captured on all the link layers
                                    PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                    1000))                                  // read timeout
            {
                // Read and dispatch packets until EOF is reached
                communicator.ReceivePackets(0, DispatcherHandler);
            }
        }

        privatestaticvoid DispatcherHandler(Packet packet)
        {
            // print packet timestamp and packet length
            Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length);

            // Print the packetconstint LineLength = 64;
            for (int i = 0; i != packet.Length; ++i)
            {
                Console.Write((packet[i]).ToString("X2"));
                if ((i + 1) % LineLength == 0)
                  Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine();
        }
    }
}

<<< PreviousNext >>>

Updated Wiki: Using Pcap.Net in your programs

$
0
0

Using Pcap.Net in your programs

Creating an application that uses Pcap.Net

To create an application that uses Pcap.Net with Microsoft Visual Studio, follow these steps:
Look at Pcap.Net Tutorial for sample programs.

Running Pcap.Net applications

To run an application that uses Pcap.Net, follow these steps:
  • Install WinPcap 4.1.2 (available at http://www.winpcap.org).
  • Install .NET Framework 4.0 (available at Microsoft Download Center).
  • Install Microsoft Visual C++ 2010 Redistributable Package (available at Microsoft Download Center: x86 version, x64 version). If you have troubles on Windows x64 versions, try installing the x86 version of the Microsoft Visual C++ 2010 Redistributable Package.

Updated Wiki: Pcap.Net Developer Guide

$
0
0
Here are the guidelines for developing Pcap.Net.
If you want to use Pcap.Net in your own application, see Pcap.Net User Guide.

Checklist

The following items are needed before you can develop Pcap.Net:

Compiling the code

  • Make sure you have the checklist.
  • Download the code (using the Source Code page or by connecting to the Source Control - if you got permissions).
  • Build PcapDotNet.sln by going over the following steps:
    • Download WinPcap Developer's Pack (of the correct WinPcap version) and put it in the Source Code 3rdParty folder (so you'll have ...\PcapDotNet\3rdParty\WpdPack\... folders).
    • Open the PcapDotNet.sln and build it.
  • Run all the unit tests of PcapDotNet.sln
  • Problems:
    • If compilation fails - try to find the problem in the Discussions page or create a new discussion.
    • If tests fail - try to find the problem in the Discussions page or create a new discussion.

Coding Conventions

  • Warning Level: 4.
  • The Resharper configuration file in the solution should be used.
  • Code Analysis should run smoothly and the following rules exceptions are allowed:
    • CA1004 (Design): Generic methods should provide type parameter
    • CA1021 (Design): Avoid out parameters
    • CA1027 (Design): Mark enums with FlagsAttribute
    • CA1028 (Design): Enum storage should be Int32
    • CA1045 (Design): Do not pass types by reference
    • CA1056 (Design): URI properties should not be strings
    • CA1501 (Maintainability): Avoid excessive inheritance
    • CA1710 (Naming): Identifiers should have correct suffix
    • CA2000 (Reliability): Dispose objects before losing scope (perhaps this rule should be enabled after it is fixed in Visual Studio 2010).
    • CA2004 (Reliability): Remove calls to GC.KeepAlive
  • Special cases to suppress Code Analysis warnings (case by case):
    • CA1025 (Design): Replace repetitive arguments with params array. Can be suppressed when it makes sense to have more than 3 parameters of the same type but not unlimited number of parameters
    • CA2227 (Usage): Collection properties should be read only - Can be suppressed only if the Collection is a ReadOnlyCollection<T>

Policies

  • Every check-in must be commented.
  • Solution must compile without errors or warnings.
  • All unit tests must pass.
  • Code coverage should be high (90%+).
  • Everything public should be documented (you should get a warning for anything that should be documented but isn't).
  • Work items of significant changes should be created. Significant changes are ones that users can notice (and so should be able to vote for).

Building the documentation

  • Build the entire PcapDotNet solution in release.
  • Download and install Sandcastle 2.6.1062.1. http://sandcastle.codeplex.com
  • Download and install Sandcastle Styles 2.6.10621.1 http://sandcastlestyles.codeplex.com
  • Download and install Sandcastle Help File Builder 1.9.3.4 Beta 2. http://shfb.codeplex.com
  • Open Pcap.Net Sandcastle Help File Builder project file located in the doc folder in the source control.
  • Make sure the version is up-to-date. If not, update it (remember to check out the file and submit it afterwards).
  • Build using Sandcastle Help File Builder.

Releasing a new version

  • Pre-release checklist:
    • Make sure the code compiles with a few warnings as possible (in release).
    • Make sure the code coverage is high.
    • Make sure the code metrics look good.
    • Build the documentation and make sure it looks good.
    • Make sure developer's pack solution compiles with updated 3rdParty binaries.
  • Versioning:
    • Decide on the new version number.
    • PcapDotNet - change the version in all the AssemblyInfo.cs files and in the AssemblyInfo.cpp file.
    • PcapDotNet.DevelopersPack - change the version in all the AssemblyInfo.cs files.
    • Documentation - change the version in the PcapDotNet.shfbproj file (requires manual checkout).
    • Checkin (note the new Change Set number).
  • Folders:
    • PcapDotNet.Source.<Version>.<Change Set>
    • PcapDotNet.Binaries.<Version>.<Change Set> containing two folders:
      • PcapDotNet.Binaries.<Version>.<Change Set>.x64
      • PcapDotNet.Binaries.<Version>.<Change Set>.x86
    • PcapDotNet.Documentation.<Version>.<Change Set>
    • PcapDotNet.DevelopersPack.<Version>.<Change Set> containing two folders:
      • PcapDotNet.DevelopersPack.<Version>.<Change Set>.x64 containing doc folder.
      • PcapDotNet.DevelopersPack.<Version>.<Change Set>.x86 containing doc folder.
  • Build:
    • Close any solution opened.
    • Do the following twice, once for x86 and once for x64:
      • Delete the bin folder of PcapDotNet.
      • Build PcapDotNet in release according to the Compiling the code section above.
      • Copy the 12 dll, xml and pdb files (not the Test, TestUtils, CodeAnalysisLog.xml or lastcodeanalysissucceeded files) from the ...\PcapDotNet\bin\Release\ folder to the previously created PcapDotNet.Binaries.<Version>.<Change Set>.<Architecture> folder.
      • Note: only the Core files should be different between the two architectures.
  • Download the Change Set source code and put its contents in the previously created PcapDotNet.Source.<Version>.<Change Set> folder.
  • Create documentation and copy it to the previously created PcapDotNet.Documentation.<Version>.<Change Set> folder.
  • Create Developer's pack:
    • Update the user guide with new versions of examples.
    • Copy the files from PcapDotNet.Source.<Version>.<Change Set> folder to the Developer's Pack folders (PcapDotNet.DevelopersPack.<Version>.<Change Set>.x64, PcapDotNet.DevelopersPack.<Version>.<Change Set>.x86).
    • Copy the files from PcapDotNet.Binaries.<Version>.<Change Set>.x64 folder to PcapDotNet.DevelopersPack.<Version>.<Change Set>.x64\PcapDotNet.DevelopersPack\3rdParty\PcapDotNet folder.
    • Copy the files from PcapDotNet.Binaries.<Version>.<Change Set>.x86 folder to PcapDotNet.DevelopersPack.<Version>.<Change Set>.x86\PcapDotNet.DevelopersPack\3rdParty\PcapDotNet folder.
    • Copy the files from PcapDotNet.Documentation.<Version>.<Change Set> to both Developer's Pack doc folders (PcapDotNet.DevelopersPack.<Version>.<Change Set>.x64\doc, PcapDotNet.DevelopersPack.<Version>.<Change Set>.x86\doc).
    • Delete all of the .vspscc and .vssscc files in the different folders under PcapDotNet.DevelopersPack.<Version>.<Change Set> folder.
  • Copy the license.txt file to PcapDotNet.Documentation.<Version>.<Change Set>, PcapDotNet.Binaries.<Version>.<Change Set> and PcapDotNet.DevelopersPack.<Version>.<Change Set> folders.
  • Zip each folder (PcapDotNet.Source.<Version>.<Change Set>, PcapDotNet.Binaries.<Version>.<Change Set>, PcapDotNet.Documentation.<Version>.<Change Set>, PcapDotNet.DevelopersPack.<Version>.<Change Set>) to create 4 matching zip files.
  • Create a new release:
    • Named it Pcap.Net <Version> (<Change Set>).
    • Copy the description from a previous release and change the necessary sections (use the comments on the different Change Sets to describe the changes).
    • The files should be ordered Developer's Pack, Binaries, Documentation, Source.
    • Developer's Pack is the recommended download.

Bugs in other products that were found during the development of Pcap.Net and were fixed:

Windows BugsWinPcap BugsWireshark Bugs

Updated Wiki: Pcap.Net Developer Guide

$
0
0
Here are the guidelines for developing Pcap.Net.
If you want to use Pcap.Net in your own application, see Pcap.Net User Guide.

Checklist

The following items are needed before you can develop Pcap.Net:

Compiling the code

  • Make sure you have the checklist.
  • Download the code (using the Source Code page or by connecting to the Source Control - if you got permissions).
  • Build PcapDotNet.sln by going over the following steps:
    • Download WinPcap Developer's Pack (of the correct WinPcap version) and put it in the Source Code 3rdParty folder (so you'll have ...\PcapDotNet\3rdParty\WpdPack\... folders).
    • Open the PcapDotNet.sln and build it.
  • Run all the unit tests of PcapDotNet.sln
  • Problems:
    • If compilation fails - try to find the problem in the Discussions page or create a new discussion.
    • If tests fail - try to find the problem in the Discussions page or create a new discussion.

Coding Conventions

  • Warning Level: 4.
  • The Resharper configuration file in the solution should be used.
  • Code Analysis should run smoothly and the following rules exceptions are allowed:
    • CA1004 (Design): Generic methods should provide type parameter
    • CA1021 (Design): Avoid out parameters
    • CA1027 (Design): Mark enums with FlagsAttribute
    • CA1028 (Design): Enum storage should be Int32
    • CA1045 (Design): Do not pass types by reference
    • CA1056 (Design): URI properties should not be strings
    • CA1501 (Maintainability): Avoid excessive inheritance
    • CA1710 (Naming): Identifiers should have correct suffix
    • CA2000 (Reliability): Dispose objects before losing scope (perhaps this rule should be enabled after it is fixed in Visual Studio 2010).
    • CA2004 (Reliability): Remove calls to GC.KeepAlive
  • Special cases to suppress Code Analysis warnings (case by case):
    • CA1025 (Design): Replace repetitive arguments with params array. Can be suppressed when it makes sense to have more than 3 parameters of the same type but not unlimited number of parameters
    • CA2227 (Usage): Collection properties should be read only - Can be suppressed only if the Collection is a ReadOnlyCollection<T>

Policies

  • Every check-in must be commented.
  • Solution must compile without errors or warnings.
  • All unit tests must pass.
  • Code coverage should be high (90%+).
  • Everything public should be documented (you should get a warning for anything that should be documented but isn't).
  • Work items of significant changes should be created. Significant changes are ones that users can notice (and so should be able to vote for).

Building the documentation

  • Build the entire PcapDotNet solution in release.
  • Download and install Sandcastle 2.6.1062.1. http://sandcastle.codeplex.com
  • Download and install Sandcastle Styles 2.6.10621.1 http://sandcastlestyles.codeplex.com
  • Download and install Sandcastle Help File Builder 1.9.3.4 Beta 2. http://shfb.codeplex.com
  • Open Pcap.Net Sandcastle Help File Builder project file located in the doc folder in the source control.
  • Make sure the version is up-to-date. If not, update it (remember to check out the file and submit it afterwards).
  • Build using Sandcastle Help File Builder.

Releasing a new version

  • Pre-release checklist:
    • Make sure the code compiles with a few warnings as possible (in release).
    • Make sure the code coverage is high.
    • Make sure the code metrics look good.
    • Build the documentation and make sure it looks good.
    • Make sure developer's pack solution compiles with updated 3rdParty binaries.
  • Versioning:
    • Decide on the new version number.
    • PcapDotNet - change the version in all the AssemblyInfo.cs files and in the AssemblyInfo.cpp file.
    • PcapDotNet.DevelopersPack - change the version in all the AssemblyInfo.cs files.
    • Documentation - change the version in the PcapDotNet.shfbproj file (requires manual checkout).
    • Checkin (note the new Change Set number).
  • Folders:
    • PcapDotNet.Source.<Version>.<Change Set>
    • PcapDotNet.Binaries.<Version>.<Change Set> containing two folders:
      • PcapDotNet.Binaries.<Version>.<Change Set>.x64
      • PcapDotNet.Binaries.<Version>.<Change Set>.x86
    • PcapDotNet.Documentation.<Version>.<Change Set>
    • PcapDotNet.DevelopersPack.<Version>.<Change Set> containing two folders:
      • PcapDotNet.DevelopersPack.<Version>.<Change Set>.x64 containing doc folder.
      • PcapDotNet.DevelopersPack.<Version>.<Change Set>.x86 containing doc folder.
  • Build:
    • Close any solution opened.
    • Do the following twice, once for x86 and once for x64:
      • Delete the bin folder of PcapDotNet.
      • Build PcapDotNet in release according to the Compiling the code section above.
      • Copy the 12 dll, xml and pdb files (not the Test, TestUtils, CodeAnalysisLog.xml or lastcodeanalysissucceeded files) from the ...\PcapDotNet\bin\Release\ folder to the previously created PcapDotNet.Binaries.<Version>.<Change Set>.<Architecture> folder.
      • Note: only the Core files should be different between the two architectures.
  • Download the Change Set source code and put its contents in the previously created PcapDotNet.Source.<Version>.<Change Set> folder.
  • Create documentation and copy it to the previously created PcapDotNet.Documentation.<Version>.<Change Set> folder.
  • Create Developer's pack:
    • Update the user guide with new versions of examples.
    • Copy the files from PcapDotNet.Source.<Version>.<Change Set> folder to the Developer's Pack folders (PcapDotNet.DevelopersPack.<Version>.<Change Set>.x64, PcapDotNet.DevelopersPack.<Version>.<Change Set>.x86).
    • Copy the files from PcapDotNet.Binaries.<Version>.<Change Set>.x64 folder to PcapDotNet.DevelopersPack.<Version>.<Change Set>.x64\PcapDotNet.DevelopersPack\3rdParty\PcapDotNet folder.
    • Copy the files from PcapDotNet.Binaries.<Version>.<Change Set>.x86 folder to PcapDotNet.DevelopersPack.<Version>.<Change Set>.x86\PcapDotNet.DevelopersPack\3rdParty\PcapDotNet folder.
    • Copy the files from PcapDotNet.Documentation.<Version>.<Change Set> to both Developer's Pack doc folders (PcapDotNet.DevelopersPack.<Version>.<Change Set>.x64\doc, PcapDotNet.DevelopersPack.<Version>.<Change Set>.x86\doc).
    • Delete all of the .vspscc and .vssscc files in the different folders under PcapDotNet.DevelopersPack.<Version>.<Change Set> folder.
  • Copy the license.txt file to PcapDotNet.Documentation.<Version>.<Change Set>, PcapDotNet.Binaries.<Version>.<Change Set> and PcapDotNet.DevelopersPack.<Version>.<Change Set> folders.
  • Zip each folder (PcapDotNet.Source.<Version>.<Change Set>, PcapDotNet.Binaries.<Version>.<Change Set>, PcapDotNet.Documentation.<Version>.<Change Set>, PcapDotNet.DevelopersPack.<Version>.<Change Set>) to create 4 matching zip files.
  • Create a new release:
    • Named it Pcap.Net <Version> (<Change Set>).
    • Copy the description from a previous release and change the necessary sections (use the comments on the different Change Sets to describe the changes).
    • The files should be ordered Developer's Pack, Binaries, Documentation, Source.
    • Developer's Pack is the recommended download.

Bugs in other products that were found during the development of Pcap.Net and were fixed:

Windows BugsWinPcap BugsWireshark Bugs

Updated Wiki: Pcap.Net Developer Guide

$
0
0
Here are the guidelines for developing Pcap.Net.
If you want to use Pcap.Net in your own application, see Pcap.Net User Guide.

Checklist

The following items are needed before you can develop Pcap.Net:

Compiling the code

  • Make sure you have the checklist.
  • Download the code (using the Source Code page or by connecting to the Source Control - if you got permissions).
  • Build PcapDotNet.sln by going over the following steps:
    • Download WinPcap Developer's Pack (of the correct WinPcap version) and put it in the Source Code 3rdParty folder (so you'll have ...\PcapDotNet\3rdParty\WpdPack\... folders).
    • Open the PcapDotNet.sln and build it.
  • Run all the unit tests of PcapDotNet.sln
  • Problems:
    • If compilation fails - try to find the problem in the Discussions page or create a new discussion.
    • If tests fail - try to find the problem in the Discussions page or create a new discussion.

Coding Conventions

  • Warning Level: 4.
  • The Resharper configuration file in the solution should be used.
  • Code Analysis should run smoothly and the following rules exceptions are allowed:
    • CA1004 (Design): Generic methods should provide type parameter
    • CA1021 (Design): Avoid out parameters
    • CA1027 (Design): Mark enums with FlagsAttribute
    • CA1028 (Design): Enum storage should be Int32
    • CA1045 (Design): Do not pass types by reference
    • CA1056 (Design): URI properties should not be strings
    • CA1501 (Maintainability): Avoid excessive inheritance
    • CA1710 (Naming): Identifiers should have correct suffix
    • CA2000 (Reliability): Dispose objects before losing scope (perhaps this rule should be enabled after it is fixed in Visual Studio 2010).
    • CA2004 (Reliability): Remove calls to GC.KeepAlive
  • Special cases to suppress Code Analysis warnings (case by case):
    • CA1025 (Design): Replace repetitive arguments with params array. Can be suppressed when it makes sense to have more than 3 parameters of the same type but not unlimited number of parameters
    • CA2227 (Usage): Collection properties should be read only - Can be suppressed only if the Collection is a ReadOnlyCollection<T>

Policies

  • Every check-in must be commented.
  • Solution must compile without errors or warnings.
  • All unit tests must pass.
  • Code coverage should be high (90%+).
  • Everything public should be documented (you should get a warning for anything that should be documented but isn't).
  • Work items of significant changes should be created. Significant changes are ones that users can notice (and so should be able to vote for).

Building the documentation

  • Build the entire PcapDotNet solution in release.
  • Download and install Sandcastle 2.6.1062.1. http://sandcastle.codeplex.com
  • Download and install Sandcastle Styles 2.6.10621.1 http://sandcastlestyles.codeplex.com
  • Download and install Sandcastle Help File Builder 1.9.3.4 Beta 2. http://shfb.codeplex.com
  • Open Pcap.Net Sandcastle Help File Builder project file located in the doc folder in the source control.
  • Make sure the version is up-to-date. If not, update it (remember to check out the file and submit it afterwards).
  • Build using Sandcastle Help File Builder.

Releasing a new version

  • Pre-release checklist:
    • Make sure the code compiles with a few warnings as possible (in release).
    • Make sure the code coverage is high.
    • Make sure the code metrics look good.
    • Build the documentation and make sure it looks good.
    • Make sure developer's pack solution compiles with updated 3rdParty binaries.
  • Versioning:
    • Decide on the new version number.
    • PcapDotNet - change the version in all the AssemblyInfo.cs files and in the AssemblyInfo.cpp file.
    • PcapDotNet.DevelopersPack - change the version in all the AssemblyInfo.cs files.
    • Documentation - change the version in the PcapDotNet.shfbproj file (requires manual checkout).
    • Checkin (note the new Change Set number).
  • Folders:
    • PcapDotNet.Source.<Version>.<Change Set>
    • PcapDotNet.Binaries.<Version>.<Change Set> containing two folders:
      • PcapDotNet.Binaries.<Version>.<Change Set>.x64
      • PcapDotNet.Binaries.<Version>.<Change Set>.x86
    • PcapDotNet.Documentation.<Version>.<Change Set>
    • PcapDotNet.DevelopersPack.<Version>.<Change Set> containing two folders:
      • PcapDotNet.DevelopersPack.<Version>.<Change Set>.x64 containing doc folder.
      • PcapDotNet.DevelopersPack.<Version>.<Change Set>.x86 containing doc folder.
  • Build:
    • Close any solution opened.
    • Do the following twice, once for x86 and once for x64:
      • Delete the bin folder of PcapDotNet.
      • Build PcapDotNet in release according to the Compiling the code section above.
      • Copy the 12 dll, xml and pdb files (not the Test, TestUtils, CodeAnalysisLog.xml or lastcodeanalysissucceeded files) from the ...\PcapDotNet\bin\Release\ folder to the previously created PcapDotNet.Binaries.<Version>.<Change Set>.<Architecture> folder.
      • Note: only the Core files should be different between the two architectures.
  • Download the Change Set source code and put its contents in the previously created PcapDotNet.Source.<Version>.<Change Set> folder.
  • Create documentation and copy it to the previously created PcapDotNet.Documentation.<Version>.<Change Set> folder.
  • Create Developer's pack:
    • Update the user guide with new versions of examples.
    • Copy the files from PcapDotNet.Source.<Version>.<Change Set> folder to the Developer's Pack folders (PcapDotNet.DevelopersPack.<Version>.<Change Set>.x64, PcapDotNet.DevelopersPack.<Version>.<Change Set>.x86).
    • Copy the files from PcapDotNet.Binaries.<Version>.<Change Set>.x64 folder to PcapDotNet.DevelopersPack.<Version>.<Change Set>.x64\PcapDotNet.DevelopersPack\3rdParty\PcapDotNet folder.
    • Copy the files from PcapDotNet.Binaries.<Version>.<Change Set>.x86 folder to PcapDotNet.DevelopersPack.<Version>.<Change Set>.x86\PcapDotNet.DevelopersPack\3rdParty\PcapDotNet folder.
    • Copy the files from PcapDotNet.Documentation.<Version>.<Change Set> to both Developer's Pack doc folders (PcapDotNet.DevelopersPack.<Version>.<Change Set>.x64\doc, PcapDotNet.DevelopersPack.<Version>.<Change Set>.x86\doc).
    • Delete all of the .vspscc and .vssscc files in the different folders under PcapDotNet.DevelopersPack.<Version>.<Change Set> folder.
  • Copy the license.txt file to PcapDotNet.Documentation.<Version>.<Change Set>, PcapDotNet.Binaries.<Version>.<Change Set> and PcapDotNet.DevelopersPack.<Version>.<Change Set> folders.
  • Zip each folder (PcapDotNet.Source.<Version>.<Change Set>, PcapDotNet.Binaries.<Version>.<Change Set>, PcapDotNet.Documentation.<Version>.<Change Set>, PcapDotNet.DevelopersPack.<Version>.<Change Set>) to create 4 matching zip files.
  • Create a new release:
    • Named it Pcap.Net <Version> (<Change Set>).
    • Copy the description from a previous release and change the necessary sections (use the comments on the different Change Sets to describe the changes).
    • The files should be ordered Developer's Pack, Binaries, Documentation, Source.
    • Developer's Pack is the recommended download.

Bugs in other products that were found during the development of Pcap.Net and were fixed:

Windows BugsWinPcap BugsWireshark Bugs

Updated Wiki: Pcap.Net Developer Guide

$
0
0
Here are the guidelines for developing Pcap.Net.
If you want to use Pcap.Net in your own application, see Pcap.Net User Guide.

Checklist

The following items are needed before you can develop Pcap.Net:

Compiling the code

  • Make sure you have the checklist.
  • Download the code (using the Source Code page or by connecting to the Source Control - if you got permissions).
  • Build PcapDotNet.sln by going over the following steps:
    • Download WinPcap Developer's Pack (of the correct WinPcap version) and put it in the Source Code 3rdParty folder (so you'll have ...\PcapDotNet\3rdParty\WpdPack\... folders).
    • Open the PcapDotNet.sln and build it.
  • Run all the unit tests of PcapDotNet.sln
  • Problems:
    • If compilation fails - try to find the problem in the Discussions page or create a new discussion.
    • If tests fail - try to find the problem in the Discussions page or create a new discussion.

Coding Conventions

  • Warning Level: 4.
  • The Resharper configuration file in the solution should be used.
  • Code Analysis should run smoothly and the following rules exceptions are allowed:
    • CA1004 (Design): Generic methods should provide type parameter
    • CA1021 (Design): Avoid out parameters
    • CA1027 (Design): Mark enums with FlagsAttribute
    • CA1028 (Design): Enum storage should be Int32
    • CA1045 (Design): Do not pass types by reference
    • CA1056 (Design): URI properties should not be strings
    • CA1501 (Maintainability): Avoid excessive inheritance
    • CA1710 (Naming): Identifiers should have correct suffix
    • CA2000 (Reliability): Dispose objects before losing scope (perhaps this rule should be enabled after it is fixed in Visual Studio 2010).
    • CA2004 (Reliability): Remove calls to GC.KeepAlive
  • Special cases to suppress Code Analysis warnings (case by case):
    • CA1025 (Design): Replace repetitive arguments with params array. Can be suppressed when it makes sense to have more than 3 parameters of the same type but not unlimited number of parameters
    • CA2227 (Usage): Collection properties should be read only - Can be suppressed only if the Collection is a ReadOnlyCollection<T>

Policies

  • Every check-in must be commented.
  • Solution must compile without errors or warnings.
  • All unit tests must pass.
  • Code coverage should be high (90%+).
  • Everything public should be documented (you should get a warning for anything that should be documented but isn't).
  • Work items of significant changes should be created. Significant changes are ones that users can notice (and so should be able to vote for).

Building the documentation

  • Build the entire PcapDotNet solution in release.
  • Download and install Sandcastle 2.6.1062.1. http://sandcastle.codeplex.com
  • Download and install Sandcastle Styles 2.6.10621.1 http://sandcastlestyles.codeplex.com
  • Download and install Sandcastle Help File Builder 1.9.3.4 Beta 2. http://shfb.codeplex.com
  • Open Pcap.Net Sandcastle Help File Builder project file located in the doc folder in the source control.
  • Make sure the version is up-to-date. If not, update it (remember to check out the file and submit it afterwards).
  • Build using Sandcastle Help File Builder.

Releasing a new version

  • Pre-release checklist:
    • Make sure the code compiles with a few warnings as possible (in release).
    • Make sure the code coverage is high.
    • Make sure the code metrics look good.
    • Build the documentation and make sure it looks good.
    • Make sure developer's pack solution compiles with updated 3rdParty binaries.
  • Versioning:
    • Decide on the new version number.
    • PcapDotNet - change the version in all the AssemblyInfo.cs files and in the AssemblyInfo.cpp file.
    • PcapDotNet.DevelopersPack - change the version in all the AssemblyInfo.cs files.
    • Documentation - change the version in the PcapDotNet.shfbproj file (requires manual checkout).
    • Checkin (note the new Change Set number).
  • Folders:
    • PcapDotNet.Source.<Version>.<Change Set>
    • PcapDotNet.Binaries.<Version>.<Change Set> containing two folders:
      • PcapDotNet.Binaries.<Version>.<Change Set>.x64
      • PcapDotNet.Binaries.<Version>.<Change Set>.x86
    • PcapDotNet.Documentation.<Version>.<Change Set>
    • PcapDotNet.DevelopersPack.<Version>.<Change Set> containing two folders:
      • PcapDotNet.DevelopersPack.<Version>.<Change Set>.x64 containing doc folder.
      • PcapDotNet.DevelopersPack.<Version>.<Change Set>.x86 containing doc folder.
  • Build:
    • Close any solution opened.
    • Do the following twice, once for x86 and once for x64:
      • Delete the bin folder of PcapDotNet.
      • Build PcapDotNet in release according to the Compiling the code section above.
      • Copy the 12 dll, xml and pdb files (not the Test, TestUtils, CodeAnalysisLog.xml or lastcodeanalysissucceeded files) from the ...\PcapDotNet\bin\Release\ folder to the previously created PcapDotNet.Binaries.<Version>.<Change Set>.<Architecture> folder.
      • Note: only the Core files should be different between the two architectures.
  • Download the Change Set source code and put its contents in the previously created PcapDotNet.Source.<Version>.<Change Set> folder.
  • Create documentation and copy it to the previously created PcapDotNet.Documentation.<Version>.<Change Set> folder.
  • Create Developer's pack:
    • Update the user guide with new versions of examples.
    • Copy the files from PcapDotNet.Source.<Version>.<Change Set> folder to the Developer's Pack folders (PcapDotNet.DevelopersPack.<Version>.<Change Set>.x64, PcapDotNet.DevelopersPack.<Version>.<Change Set>.x86).
    • Copy the files from PcapDotNet.Binaries.<Version>.<Change Set>.x64 folder to PcapDotNet.DevelopersPack.<Version>.<Change Set>.x64\PcapDotNet.DevelopersPack\3rdParty\PcapDotNet folder.
    • Copy the files from PcapDotNet.Binaries.<Version>.<Change Set>.x86 folder to PcapDotNet.DevelopersPack.<Version>.<Change Set>.x86\PcapDotNet.DevelopersPack\3rdParty\PcapDotNet folder.
    • Copy the files from PcapDotNet.Documentation.<Version>.<Change Set> to both Developer's Pack doc folders (PcapDotNet.DevelopersPack.<Version>.<Change Set>.x64\doc, PcapDotNet.DevelopersPack.<Version>.<Change Set>.x86\doc).
    • Delete all of the .vspscc and .vssscc files in the different folders under PcapDotNet.DevelopersPack.<Version>.<Change Set> folder.
  • Copy the license.txt file to PcapDotNet.Documentation.<Version>.<Change Set>, PcapDotNet.Binaries.<Version>.<Change Set> and PcapDotNet.DevelopersPack.<Version>.<Change Set> folders.
  • Zip each folder (PcapDotNet.Source.<Version>.<Change Set>, PcapDotNet.Binaries.<Version>.<Change Set>, PcapDotNet.Documentation.<Version>.<Change Set>, PcapDotNet.DevelopersPack.<Version>.<Change Set>) to create 4 matching zip files.
  • Create a new release:
    • Named it Pcap.Net <Version> (<Change Set>).
    • Copy the description from a previous release and change the necessary sections (use the comments on the different Change Sets to describe the changes).
    • The files should be ordered Developer's Pack, Binaries, Documentation, Source.
    • Developer's Pack is the recommended download.

Bugs in other products that were found during the development of Pcap.Net and were fixed:

Windows BugsWinPcap BugsWireshark Bugs

New Comment on "Pcap.Net Tutorial - Interpreting the packets"

$
0
0
why my result is so strange ip: 2012-10-14 08:58:58.513 length:980 8.0.69.0:8-->3.198.24.71:51845 ------------ 2012-10-14 08:58:58.697 length:289 8.0.69.0:36464-->1.19.97.42:23120 ------------ 2012-10-14 08:58:58.771 length:880 8.0.69.0:8-->3.98.29.200:51845 ------------ 2012-10-14 08:58:58.815 length:55 8.0.69.0:26440-->0.41.97.43:23053 ------------ 2012-10-14 08:58:58.965 length:54 8.0.69.0:36464-->0.40.97.44:23120 ------------ 2012-10-14 08:58:59.089 length:60 8.0.69.0:8-->0.40.157.113:51845 ------------ 2012-10-14 08:58:59.770 length:54 8.0.69.0:8-->0.40.51.119:51845 ------------ 2012-10-14 08:58:59.770 length:54 8.0.69.0:36464-->0.40.97.45:23120

New Comment on "Pcap.Net Tutorial - Interpreting the packets"

$
0
0
why my result is so strange ,these ips : 2012-10-14 08:58:58.513 length:980 8.0.69.0:8-->3.198.24.71:51845 ------------ 2012-10-14 08:58:58.697 length:289 8.0.69.0:36464-->1.19.97.42:23120 ------------ 2012-10-14 08:58:58.771 length:880 8.0.69.0:8-->3.98.29.200:51845 ------------ 2012-10-14 08:58:58.815 length:55 8.0.69.0:26440-->0.41.97.43:23053 ------------ 2012-10-14 08:58:58.965 length:54 8.0.69.0:36464-->0.40.97.44:23120 ------------ 2012-10-14 08:58:59.089 length:60 8.0.69.0:8-->0.40.157.113:51845 ------------ 2012-10-14 08:58:59.770 length:54 8.0.69.0:8-->0.40.51.119:51845 ------------ 2012-10-14 08:58:59.770 length:54 8.0.69.0:36464-->0.40.97.45:23120
Viewing all 114 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>