To create a custom network packet, you instantiate individual protocol packets and then 'stitch' them together by assigning them to the PayloadPacket property of the layer above them.
Example: Constructing an Ethernet -> IPv4 -> TCP packet
using PacketDotNet;
// 1. Create the innermost layer (TCP)
ushort tcpSourcePort = 123;
ushort tcpDestinationPort = 321;
var tcpPacket = new TcpPacket(tcpSourcePort, tcpDestinationPort);
// 2. Create the middle layer (IPv4)
var ipSourceAddress = System.Net.IPAddress.Parse("192.168.1.1");
var ipDestinationAddress = System.Net.IPAddress.Parse("192.168.1.2");
var ipPacket = new IPv4Packet(ipSourceAddress, ipDestinationAddress);
// 3. Create the outermost layer (Ethernet)
var sourceHwAddress = "90-90-90-90-90-90";
var ethernetSourceHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(sourceHwAddress);
var destinationHwAddress = "80-80-80-80-80-80";
var ethernetDestinationHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(destinationHwAddress);
// EthernetPacketType.None allows the protocol type to be updated based on the payload
var ethernetPacket = new EthernetPacket(ethernetSourceHwAddress,
ethernetDestinationHwAddress,
EthernetPacketType.None);
// 4. Stitch the packets together
ipPacket.PayloadPacket = tcpPacket;
ethernetPacket.PayloadPacket = ipPacket;
// 5. Use the packet
Console.WriteLine(ethernetPacket.ToString());
byte[] packetBytes = ethernetPacket.Bytes;
using PacketDotNet;
ushort tcpSourcePort = 123;
ushort tcpDestinationPort = 321;
var tcpPacket = new TcpPacket(tcpSourcePort, tcpDestinationPort);
var ipSourceAddress = System.Net.IPAddress.Parse("192.168.1.1");
var ipDestinationAddress = System.Net.IPAddress.Parse("192.168.1.2");
var ipPacket = new IPv4Packet(ipSourceAddress, ipDestinationAddress);
var sourceHwAddress = "90-90-90-90-90-90";
var ethernetSourceHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(sourceHwAddress);
var destinationHwAddress = "80-80-80-80-80-80";
var ethernetDestinationHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(destinationHwAddress);
// NOTE: using EthernetPacketType.None to illustrate that the Ethernet
// protocol type is updated based on the packet payload that is
// assigned to that particular Ethernet packet
var ethernetPacket = new EthernetPacket(ethernetSourceHwAddress,
ethernetDestinationHwAddress,
EthernetPacketType.None);
// Now stitch all of the packets together
ipPacket.PayloadPacket = tcpPacket;
ethernetPacket.PayloadPacket = ipPacket;
// and print out the packet to see that it looks just like we wanted it to
Console.WriteLine(ethernetPacket.ToString());
// to retrieve the bytes that represent this newly created EthernetPacket use the Bytes property
byte[] packetBytes = ethernetPacket.Bytes;