/// <summary>
        /// This function builds the Ethernet Row Data Packet with every third channel set to a color.
        /// </summary>
        private Packet BuildTestPacket(MacAddress source, MacAddress destination, int row, int pixelsWidth, int dataOffset, byte color, int testOffset)
        {
            int offset = 0;
            int width  = pixelsWidth * 3;

            byte[] mainByte = new byte[(width) + 7];

            EthernetType type = ((EthernetType)0x5500);

            if (row < 256)
            {
                type        = ((EthernetType)0x5500);
                mainByte[0] = Convert.ToByte(row);
            }
            else
            {
                type        = ((EthernetType)0x5501);
                mainByte[0] = Convert.ToByte(row % 256);
            }

            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = source,
                Destination = destination,
                EtherType   = type
            };

            //mainByte[0] = Convert.ToByte(row);
            mainByte[1] = Convert.ToByte(offset >> 8);
            mainByte[2] = Convert.ToByte(offset & 0xFF);
            mainByte[3] = Convert.ToByte(pixelsWidth >> 8);
            mainByte[4] = Convert.ToByte(pixelsWidth & 0xFF);
            mainByte[5] = 0x08;
            mainByte[6] = 0x80;

            for (int i = 0; i < width; i++)
            {
                int  indexwHead = 7 + i;
                byte oldValue   = 0;
                if (i % 3 == testOffset)
                {
                    oldValue = color;
                }
                //int oldint = Convert.ToInt32(data[i + (fullDataOffset * 3)]);
                int  newint   = ((oldValue * _brightness) / 100);
                byte newValue = Convert.ToByte(newint);
                mainByte[indexwHead] = newValue;
                //mainByte[indexwHead] = 0x88;
            }

            PayloadLayer payloadLayer =
                new PayloadLayer
            {
                Data = new Datagram(mainByte)
            };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, payloadLayer);

            return(builder.Build(DateTime.Now));
        }
Example #2
0
        public void RandomUdpTest()
        {
            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = new MacAddress("00:01:02:03:04:05"),
                Destination = new MacAddress("A0:A1:A2:A3:A4:A5")
            };

            int seed = new Random().Next();

            Console.WriteLine("Seed: " + seed);
            Random random = new Random(seed);

            for (int i = 0; i != 1000; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
                ipV4Layer.HeaderChecksum = null;
                IpV6Layer ipV6Layer = random.NextIpV6Layer(IpV4Protocol.Udp, false);

                EthernetType ethernetType = random.NextBool() ? EthernetType.IpV4 : EthernetType.IpV6;
                Layer        ipLayer      = (ethernetType == EthernetType.IpV4 ? (Layer)ipV4Layer : ipV6Layer);
                UdpLayer     udpLayer     = random.NextUdpLayer();
                udpLayer.Checksum = null;

                PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(60000));

                Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, udpLayer, payloadLayer);

                Assert.IsTrue(packet.IsValid, "IsValid");

                // Ethernet
                ethernetLayer.EtherType = ethernetType;
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");
                ethernetLayer.EtherType = EthernetType.None;

                // Ip
                if (ipLayer == ipV4Layer)
                {
                    // IpV4.
                    ipV4Layer.Protocol       = IpV4Protocol.Udp;
                    ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
                    Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IP Layer");
                    ipV4Layer.HeaderChecksum = null;
                }
                else
                {
                    // IpV6.
                    Assert.AreEqual(ipV6Layer, packet.Ethernet.IpV6.ExtractLayer(), "IP Layer");
                }

                // UDP
                udpLayer.Checksum = packet.Ethernet.Ip.Udp.Checksum;
                Assert.AreEqual(udpLayer, packet.Ethernet.Ip.Udp.ExtractLayer(), "UDP Layer");
                Assert.AreEqual(UdpDatagram.HeaderLength + payloadLayer.Length, packet.Ethernet.Ip.Udp.TotalLength, "Total Length");
                Assert.IsTrue(!udpLayer.CalculateChecksum && packet.Ethernet.Ip.Udp.Checksum == 0 ||
                              udpLayer.CalculateChecksum && packet.Ethernet.Ip.IsTransportChecksumCorrect, "IsTransportChecksumCorrect");
                Assert.IsTrue(packet.Ethernet.Ip.Udp.IsChecksumOptional, "IsChecksumOptional");
                Assert.AreEqual(payloadLayer.Data, packet.Ethernet.Ip.Udp.Payload, "Payload");
            }
        }
 public static EthernetLayer NextEthernetLayer(this Random random, EthernetType etherType)
 {
     return new EthernetLayer
            {
                Source = random.NextMacAddress(),
                Destination = random.NextMacAddress(),
                EtherType = etherType
            };
 }
Example #4
0
 public static EthernetLayer NextEthernetLayer(this Random random, EthernetType etherType)
 {
     return(new EthernetLayer
     {
         Source = random.NextMacAddress(),
         Destination = random.NextMacAddress(),
         EtherType = etherType
     });
 }
 public static VLanTaggedFrameLayer NextVLanTaggedFrameLayer(this Random random, EthernetType etherType)
 {
     return new VLanTaggedFrameLayer
            {
                PriorityCodePoint = random.NextEnum<ClassOfService>(),
                CanonicalFormatIndicator = random.NextBool(),
                VLanIdentifier = random.NextUShort(VLanTaggedFrameDatagram.MaxVLanIdentifier + 1),
                EtherType = etherType,
            };
 }
Example #6
0
        public static double GetCapacity(EthernetType ethernetType, int byteFrameLength, bool useMiliSeconds = true)
        {
            if (!IsRightFrameLength(byteFrameLength))
            {
                throw new ArgumentOutOfRangeException("byteFrameLength",
                                                      String.Format("Frame length must be between {0} and {1}", (int)FrameLength.Min, (int)FrameLength.Max));
            }

            return(1.0 /
                   (GetBitInterval(ethernetType) * (8 * byteFrameLength + 96) * (useMiliSeconds? Math.Pow(10, 3) : 1)));
        }
        public EthernetComm(string host, int port, EthernetType type)  // 初始化
        {
            _IPAddress    = host;
            _Port         = port;
            _EthernetType = type;

            _IP          = IPAddress.Parse(host);
            _IPE         = new IPEndPoint(_IP, port);
            _IsConnected = false;
            _Socket      = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }
Example #8
0
        public override void Write(byte[] buffer, int offset, int payloadLength, ILayer previousLayer, ILayer nextLayer)
        {
            EthernetType       ethernetType      = EthernetBaseLayer.GetEthernetType(this.EtherType, nextLayer);
            MacAddress         destination       = this.Destination;
            IEthernetNextLayer ethernetNextLayer = nextLayer as IEthernetNextLayer;

            if (destination == MacAddress.Zero && ethernetNextLayer != null && ethernetNextLayer.PreviousLayerDefaultDestination.HasValue)
            {
                destination = ethernetNextLayer.PreviousLayerDefaultDestination.Value;
            }
            EthernetDatagram.WriteHeader(buffer, offset, this.Source, destination, ethernetType);
        }
Example #9
0
        internal static EthernetType GetEthernetType(EthernetType ethernetType, ILayer nextLayer)
        {
            if (ethernetType != EthernetType.None)
                return ethernetType;

            if (nextLayer == null)
                throw new ArgumentException("Can't determine ether type automatically from next layer because there is not next layer");
            IEthernetNextLayer ethernetNextLayer = nextLayer as IEthernetNextLayer;
            if (ethernetNextLayer == null)
                throw new ArgumentException("Can't determine ether type automatically from next layer (" + nextLayer.GetType() + ")");

            return ethernetNextLayer.PreviousLayerEtherType;
        }
Example #10
0
 internal static void WriteHeader(byte[] buffer, int offset,
                                  ArpHardwareType hardwareType, EthernetType protocolType, ArpOperation operation,
                                  IList <byte> senderHardwareAddress, IList <byte> senderProtocolAddress,
                                  IList <byte> targetHardwareAddress, IList <byte> targetProtocolAddress)
 {
     buffer.Write(ref offset, (ushort)hardwareType, Endianity.Big);
     buffer.Write(ref offset, (ushort)protocolType, Endianity.Big);
     buffer.Write(ref offset, (byte)senderHardwareAddress.Count);
     buffer.Write(ref offset, (byte)senderProtocolAddress.Count);
     buffer.Write(ref offset, (ushort)operation, Endianity.Big);
     buffer.Write(ref offset, senderHardwareAddress);
     buffer.Write(ref offset, senderProtocolAddress);
     buffer.Write(ref offset, targetHardwareAddress);
     buffer.Write(ref offset, targetProtocolAddress);
 }
Example #11
0
 public static string GetEthernetTypeCode(EthernetType ethernetType)
 {
     switch (ethernetType)
     {
         case global::PcapDotNet.Packets.Ethernet.EthernetType.None: return "None";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.IpV4: return "IPv4";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.Arp: return "ARP";
         //case EtherType::WakeOnLan:                                                         return "WakeOnLan";
         //case EtherType::SYN3Heartbeat:                                                     return "SYNdog";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.ReverseArp: return "RARP";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.AppleTalk: return "AppleTalk";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.AppleTalkArp: return "AARP";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.VLanTaggedFrame: return "VLAN";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.NovellInternetworkPacketExchange: return "NovellIPX";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.Novell: return "Novell";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.IpV6: return "IPv6";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.MacControl: return "MACControl";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.PointToPointProtocol: return "PPP";
         //case EtherType::SlowProtocols:                                                     return "SlowProtocols";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.CobraNet: return "CobraNet";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.MultiprotocolLabelSwitchingUnicast: return "MPLSUnicast";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.MultiprotocolLabelSwitchingMulticast: return "MPLSMulticast";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.PointToPointProtocolOverEthernetDiscoveryStage: return "PPPoEDiscoveryStage";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.PointToPointProtocolOverEthernetSessionStage: return "PPPoESessionStage";
         //case EtherType::MicrosoftNLB:                                                      return "MicrosoftNLB";
         //case EtherType::JumboFrames:                                                       return "JumboFrames";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.ExtensibleAuthenticationProtocolOverLan: return "EAPOverLAN";
         //case EtherType::Profinet:                                                          return "Profinet";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.HyperScsi: return "HyperSCSI";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.AtaOverEthernet: return "ATAOverEthernet";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.EtherCatProtocol: return "EtherCAT";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.ProviderBridging: return "ProviderBridging";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.AvbTransportProtocol: return "AVBTP";
         //case EtherType::EthernetPowerlink:                                                 return "EthernetPowerlink";
         //case EtherType::LLDP:                                                              return "LLDP";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.SerialRealTimeCommunicationSystemIii: return "SercosIII";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.CircuitEmulationServicesOverEthernet: return "MEF-8";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.HomePlug: return "HomePlug";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.MacSecurity: return "MACSecurity";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.PrecisionTimeProtocol: return "PrecisionTime";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.ConnectivityFaultManagementOrOperationsAdministrationManagement: return "CFM";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.FibreChannelOverEthernet: return "FibreChannel";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.FibreChannelOverEthernetInitializationProtocol: return "FCoEInitialization";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.QInQ: return "QinQ";
         case global::PcapDotNet.Packets.Ethernet.EthernetType.VeritasLowLatencyTransport: return "LLT";
         default: return "Unknown";
     }
 }
        public Datagram Get(EthernetType ethernetType)
        {
            switch (ethernetType)
            {
            case EthernetType.IpV4:
                return(IpV4);

            case EthernetType.Arp:
                return(Arp);

            case EthernetType.VLanTaggedFrame:
                return(VLanTaggedFrame);

            default:
                return(null);
            }
        }
        public Datagram Get(EthernetType ethernetType)
        {
            switch (ethernetType)
            {
                case EthernetType.IpV4:
                    return IpV4;

                case EthernetType.Arp:
                    return Arp;

                case EthernetType.VLanTaggedFrame:
                    return VLanTaggedFrame;

                default:
                    return null;
            }
        }
Example #14
0
        internal static EthernetType GetEthernetType(EthernetType ethernetType, ILayer nextLayer)
        {
            if (ethernetType != EthernetType.None)
            {
                return(ethernetType);
            }
            if (nextLayer == null)
            {
                throw new ArgumentException("Can't determine ether type automatically from next layer because there is not next layer");
            }
            IEthernetNextLayer ethernetNextLayer = nextLayer as IEthernetNextLayer;

            if (ethernetNextLayer == null)
            {
                throw new ArgumentException("Can't determine ether type automatically from next layer (" + (object)nextLayer.GetType() + ")");
            }
            return(ethernetNextLayer.PreviousLayerEtherType);
        }
Example #15
0
        public override void Write(byte[] buffer, int offset, int payloadLength, ILayer previousLayer, ILayer nextLayer)
        {
            EthernetType protocolType = this.ProtocolType;

            if (protocolType == EthernetType.None)
            {
                if (nextLayer == null)
                {
                    throw new ArgumentException("Can't determine protocol type automatically from next layer because there is not next layer");
                }
                IEthernetNextLayer ethernetNextLayer = nextLayer as IEthernetNextLayer;
                if (ethernetNextLayer == null)
                {
                    throw new ArgumentException("Can't determine protocol type automatically from next layer (" + (object)nextLayer.GetType() + ")");
                }
                protocolType = ethernetNextLayer.PreviousLayerEtherType;
            }
            GreDatagram.WriteHeader(buffer, offset, this.RecursionControl, this.FutureUseBits, this.Version, protocolType, this.ChecksumPresent, this.Key, this.SequenceNumber, this.AcknowledgmentSequenceNumber, this.Routing, this.RoutingOffset, this.StrictSourceRoute);
        }
Example #16
0
#pragma warning restore 0169, 0649
#endif

        /// <summary>
        /// Construct a new ethernet packet from source and destination mac addresses
        /// </summary>
        public EthernetPacket
        (
            PhysicalAddress sourceHardwareAddress,
            PhysicalAddress destinationHardwareAddress,
            EthernetType ethernetType)
        {
            Log.Debug("");

            // allocate memory for this packet
            var length      = EthernetFields.HeaderLength;
            var headerBytes = new byte[length];

            Header = new ByteArraySegment(headerBytes, 0, length);

            // set the instance values
            SourceHardwareAddress      = sourceHardwareAddress;
            DestinationHardwareAddress = destinationHardwareAddress;
            Type = ethernetType;
        }
 internal static void WriteHeader(byte[] buffer, int offset, byte recursionControl, byte flags, GreVersion version, EthernetType protocolType, bool checksumPresent, uint?key, uint?sequenceNumber, uint?acknowledgmentSequenceNumber, ReadOnlyCollection <GreSourceRouteEntry> routing, ushort?routingOffset, bool strictSourceRoute)
 {
     ByteArrayExtensions.Write(buffer, offset, (byte)((checksumPresent ? 128 : 0) | (routing != null ? 64 : 0) | (key.HasValue ? 32 : 0) | (sequenceNumber.HasValue ? 16 : 0) | (strictSourceRoute ? 8 : 0) | (int)recursionControl & 7));
     ByteArrayExtensions.Write(buffer, offset + 1, (byte)((GreVersion)((acknowledgmentSequenceNumber.HasValue ? 128 : 0) | (int)flags << 3 & 120) | version & (GreVersion)7));
     ByteArrayExtensions.Write(buffer, offset + 2, (ushort)protocolType, Endianity.Big);
     offset += 4;
     if (checksumPresent || routing != null)
     {
         offset += 2;
         ushort?nullable = routingOffset;
         if ((nullable.HasValue ? new int?((int)nullable.GetValueOrDefault()) : new int?()).HasValue)
         {
             ByteArrayExtensions.Write(buffer, offset, routingOffset.Value, Endianity.Big);
         }
         offset += 2;
     }
     if (key.HasValue)
     {
         ByteArrayExtensions.Write(buffer, ref offset, key.Value, Endianity.Big);
     }
     if (sequenceNumber.HasValue)
     {
         ByteArrayExtensions.Write(buffer, ref offset, sequenceNumber.Value, Endianity.Big);
     }
     if (acknowledgmentSequenceNumber.HasValue)
     {
         ByteArrayExtensions.Write(buffer, ref offset, acknowledgmentSequenceNumber.Value, Endianity.Big);
     }
     if (routing == null)
     {
         return;
     }
     foreach (GreSourceRouteEntry sourceRouteEntry in routing)
     {
         sourceRouteEntry.Write(buffer, ref offset);
     }
     ByteArrayExtensions.Write(buffer, ref offset, 0U, Endianity.Big);
 }
Example #18
0
 internal static void WriteHeader(byte[] buffer, int offset,
                                  ArpHardwareType hardwareType, EthernetType protocolType, ArpOperation operation,
                                  IList<byte> senderHardwareAddress, IList<byte> senderProtocolAddress,
                                  IList<byte> targetHardwareAddress, IList<byte> targetProtocolAddress)
 {
     buffer.Write(ref offset, (ushort)hardwareType, Endianity.Big);
     buffer.Write(ref offset, (ushort)protocolType, Endianity.Big);
     buffer.Write(ref offset, (byte)senderHardwareAddress.Count);
     buffer.Write(ref offset, (byte)senderProtocolAddress.Count);
     buffer.Write(ref offset, (ushort)operation, Endianity.Big);
     buffer.Write(ref offset, senderHardwareAddress);
     buffer.Write(ref offset, senderProtocolAddress);
     buffer.Write(ref offset, targetHardwareAddress);
     buffer.Write(ref offset, targetProtocolAddress);
 }
Example #19
0
 internal static void WriteHeader(byte[] buffer, int offset, MacAddress ethernetSource, MacAddress ethernetDestination, EthernetType ethernetType)
 {
     ByteArrayExtensions.Write(buffer, offset + 6, ethernetSource, Endianity.Big);
     ByteArrayExtensions.Write(buffer, offset, ethernetDestination, Endianity.Big);
     ByteArrayExtensions.Write(buffer, offset + 12, (ushort)ethernetType, Endianity.Big);
 }
 internal static void WriteHeader(byte[] buffer, int offset, ClassOfService priorityCodePoint, bool canonicalFormatIndicator, ushort vLanIdentifier, EthernetType etherType)
 {
     ushort tagControlInformation = CalculateTagControlInformation(priorityCodePoint, canonicalFormatIndicator, vLanIdentifier);
     buffer.Write(offset + Offset.PriorityCodePoint, tagControlInformation, Endianity.Big);
     buffer.Write(offset + Offset.EtherTypeLength, (ushort)etherType, Endianity.Big);
 }
Example #21
0
        public void RandomTcpTest()
        {
            MacAddress ethernetSource      = new MacAddress("00:01:02:03:04:05");
            MacAddress ethernetDestination = new MacAddress("A0:A1:A2:A3:A4:A5");

            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = ethernetSource,
                Destination = ethernetDestination
            };

            int seed = new Random().Next();

            Console.WriteLine("Seed: " + seed);
            Random random = new Random(seed);

            for (int i = 0; i != 1000; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
                ipV4Layer.HeaderChecksum = null;
                IpV6Layer ipV6Layer = random.NextIpV6Layer(IpV4Protocol.Tcp, false);

                EthernetType ethernetType = random.NextBool() ? EthernetType.IpV4 : EthernetType.IpV6;
                Layer        ipLayer      = (ethernetType == EthernetType.IpV4 ? (Layer)ipV4Layer : ipV6Layer);
                TcpLayer     tcpLayer     = random.NextTcpLayer();

                PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(60000));

                Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, tcpLayer, payloadLayer);

                Assert.IsTrue(packet.IsValid);

                // Ethernet
                ethernetLayer.EtherType = ethernetType;
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");
                ethernetLayer.EtherType = EthernetType.None;

                // Ip.
                if (ipLayer == ipV4Layer)
                {
                    // IpV4.
                    ipV4Layer.Protocol       = IpV4Protocol.Tcp;
                    ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
                    Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IPv4 Layer");
                    ipV4Layer.HeaderChecksum = null;
                }
                else
                {
                    Assert.AreEqual(ipV6Layer, packet.Ethernet.IpV6.ExtractLayer(), "IPv6 Layer");
                }

                // TCP
                tcpLayer.Checksum = packet.Ethernet.Ip.Tcp.Checksum;
                Assert.AreEqual(tcpLayer, packet.Ethernet.Ip.Tcp.ExtractLayer(), "TCP Layer");
                Assert.AreNotEqual(random.NextTcpLayer(), packet.Ethernet.Ip.Tcp.ExtractLayer(), "TCP Layer");
                Assert.AreEqual(tcpLayer.GetHashCode(), packet.Ethernet.Ip.Tcp.ExtractLayer().GetHashCode(), "TCP Layer");
                Assert.AreNotEqual(random.NextTcpLayer().GetHashCode(), packet.Ethernet.Ip.Tcp.ExtractLayer().GetHashCode(), "TCP Layer");
                Assert.AreEqual((uint)(packet.Ethernet.Ip.Tcp.SequenceNumber + packet.Ethernet.Ip.Tcp.PayloadLength), packet.Ethernet.Ip.Tcp.NextSequenceNumber);
                foreach (TcpOption option in packet.Ethernet.Ip.Tcp.Options.OptionsCollection)
                {
                    Assert.AreEqual(option, option);
                    Assert.AreEqual(option.GetHashCode(), option.GetHashCode());
                    Assert.IsFalse(string.IsNullOrEmpty(option.ToString()));
                    Assert.IsFalse(option.Equals(null));
                    Assert.IsFalse(option.Equals(2));
                }
                Assert.AreEqual(tcpLayer.Options, packet.Ethernet.Ip.Tcp.Options, "Options");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Acknowledgment) == TcpControlBits.Acknowledgment, packet.Ethernet.Ip.Tcp.IsAcknowledgment, "IsAcknowledgment");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.CongestionWindowReduced) == TcpControlBits.CongestionWindowReduced, packet.Ethernet.Ip.Tcp.IsCongestionWindowReduced, "IsCongestionWindowReduced");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.ExplicitCongestionNotificationEcho) == TcpControlBits.ExplicitCongestionNotificationEcho, packet.Ethernet.Ip.Tcp.IsExplicitCongestionNotificationEcho, "IsExplicitCongestionNotificationEcho");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Fin) == TcpControlBits.Fin, packet.Ethernet.Ip.Tcp.IsFin, "IsFin");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Push) == TcpControlBits.Push, packet.Ethernet.Ip.Tcp.IsPush, "IsPush");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Reset) == TcpControlBits.Reset, packet.Ethernet.Ip.Tcp.IsReset, "IsReset");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Synchronize) == TcpControlBits.Synchronize, packet.Ethernet.Ip.Tcp.IsSynchronize, "IsSynchronize");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Urgent) == TcpControlBits.Urgent, packet.Ethernet.Ip.Tcp.IsUrgent, "IsUrgent");
                Assert.AreEqual(0, packet.Ethernet.Ip.Tcp.Reserved);
                Assert.IsFalse(packet.Ethernet.Ip.Tcp.IsChecksumOptional, "IsChecksumOptional");
                Assert.AreEqual(TcpDatagram.HeaderMinimumLength + tcpLayer.Options.BytesLength + payloadLayer.Length, packet.Ethernet.Ip.Tcp.Length, "Total Length");
                Assert.IsTrue(packet.Ethernet.Ip.IsTransportChecksumCorrect, "IsTransportChecksumCorrect");

                Assert.AreEqual(payloadLayer.Data, packet.Ethernet.Ip.Tcp.Payload, "Payload");
            }
        }
Example #22
0
 public static double GetCapacity(EthernetType ethernetType, FrameLength byteFrameLength, bool useMiliSeconds = true)
 {
     return(GetCapacity(ethernetType, (int)byteFrameLength, useMiliSeconds));
 }
Example #23
0
        public static string GetEthernetTypeCode(EthernetType ethernetType)
        {
            switch (ethernetType)
            {
            case global::PcapDotNet.Packets.Ethernet.EthernetType.None: return("None");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.IpV4: return("IPv4");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.Arp: return("ARP");

            //case EtherType::WakeOnLan:                                                         return "WakeOnLan";
            //case EtherType::SYN3Heartbeat:                                                     return "SYNdog";
            case global::PcapDotNet.Packets.Ethernet.EthernetType.ReverseArp: return("RARP");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.AppleTalk: return("AppleTalk");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.AppleTalkArp: return("AARP");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.VLanTaggedFrame: return("VLAN");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.NovellInternetworkPacketExchange: return("NovellIPX");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.Novell: return("Novell");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.IpV6: return("IPv6");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.MacControl: return("MACControl");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.PointToPointProtocol: return("PPP");

            //case EtherType::SlowProtocols:                                                     return "SlowProtocols";
            case global::PcapDotNet.Packets.Ethernet.EthernetType.CobraNet: return("CobraNet");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.MultiprotocolLabelSwitchingUnicast: return("MPLSUnicast");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.MultiprotocolLabelSwitchingMulticast: return("MPLSMulticast");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.PointToPointProtocolOverEthernetDiscoveryStage: return("PPPoEDiscoveryStage");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.PointToPointProtocolOverEthernetSessionStage: return("PPPoESessionStage");

            //case EtherType::MicrosoftNLB:                                                      return "MicrosoftNLB";
            //case EtherType::JumboFrames:                                                       return "JumboFrames";
            case global::PcapDotNet.Packets.Ethernet.EthernetType.ExtensibleAuthenticationProtocolOverLan: return("EAPOverLAN");

            //case EtherType::Profinet:                                                          return "Profinet";
            case global::PcapDotNet.Packets.Ethernet.EthernetType.HyperScsi: return("HyperSCSI");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.AtaOverEthernet: return("ATAOverEthernet");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.EtherCatProtocol: return("EtherCAT");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.ProviderBridging: return("ProviderBridging");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.AvbTransportProtocol: return("AVBTP");

            //case EtherType::EthernetPowerlink:                                                 return "EthernetPowerlink";
            //case EtherType::LLDP:                                                              return "LLDP";
            case global::PcapDotNet.Packets.Ethernet.EthernetType.SerialRealTimeCommunicationSystemIii: return("SercosIII");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.CircuitEmulationServicesOverEthernet: return("MEF-8");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.HomePlug: return("HomePlug");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.MacSecurity: return("MACSecurity");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.PrecisionTimeProtocol: return("PrecisionTime");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.ConnectivityFaultManagementOrOperationsAdministrationManagement: return("CFM");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.FibreChannelOverEthernet: return("FibreChannel");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.FibreChannelOverEthernetInitializationProtocol: return("FCoEInitialization");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.QInQ: return("QinQ");

            case global::PcapDotNet.Packets.Ethernet.EthernetType.VeritasLowLatencyTransport: return("LLT");

            default: return("Unknown");
            }
        }
Example #24
0
        public void RandomIpV4Test()
        {
            MacAddress         ethernetSource      = new MacAddress("00:01:02:03:04:05");
            MacAddress         ethernetDestination = new MacAddress("A0:A1:A2:A3:A4:A5");
            const EthernetType EthernetType        = EthernetType.IpV4;

            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = ethernetSource,
                Destination = ethernetDestination,
                EtherType   = EthernetType
            };

            int seed = new Random().Next();

            Console.WriteLine(seed);
            Random random = new Random(seed);

            for (int i = 0; i != 1000; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer();
                ipV4Layer.HeaderChecksum = null;

                PayloadLayer payloadLayer = random.NextPayloadLayer(random.NextInt(0, 50 * 1024));

                Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipV4Layer, payloadLayer);

                Assert.IsTrue(ipV4Layer.Protocol == IpV4Protocol.Ip ||
                              ipV4Layer.Protocol == IpV4Protocol.IpV6 ||
                              ipV4Layer.Protocol == IpV4Protocol.Udp ||
                              ipV4Layer.Protocol == IpV4Protocol.Tcp ||
                              ipV4Layer.Protocol == IpV4Protocol.InternetGroupManagementProtocol ||
                              ipV4Layer.Protocol == IpV4Protocol.InternetControlMessageProtocol ||
                              ipV4Layer.Protocol == IpV4Protocol.Gre ||
                              packet.IsValid, "IsValid (" + ipV4Layer.Protocol + ")");

                // Ethernet
                Assert.AreEqual(packet.Length - EthernetDatagram.HeaderLengthValue, packet.Ethernet.PayloadLength, "PayloadLength");
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");

                // IpV4
                ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
                Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IP Layer");
                Assert.AreEqual(ipV4Layer.Destination, packet.Ethernet.IpV4.Destination, "Destination");
                Assert.AreNotEqual(ipV4Layer, null);
                Assert.AreNotEqual(ipV4Layer, new PayloadLayer());
                Assert.IsNotNull(ipV4Layer.ToString());
                Assert.AreEqual(IpV4Datagram.HeaderMinimumLength + ipV4Layer.Options.BytesLength, packet.Ethernet.IpV4.HeaderLength, "IP HeaderLength");
                Assert.AreEqual(packet.Length - EthernetDatagram.HeaderLengthValue, packet.Ethernet.IpV4.TotalLength, "IP TotalLength");
                Assert.AreNotEqual(2, packet.Ethernet.IpV4.Fragmentation, "IP Fragmentation");
                Assert.IsTrue(ipV4Layer.Fragmentation == packet.Ethernet.IpV4.Fragmentation, "IP Fragmentation");
                Assert.IsFalse(ipV4Layer.Fragmentation != packet.Ethernet.IpV4.Fragmentation, "IP Fragmentation");
                Assert.IsFalse(ipV4Layer.Fragmentation.Equals(0), "IP Fragmentation");
                if (ipV4Layer.Fragmentation.Offset != 0)
                {
                    Assert.AreNotEqual(ipV4Layer.Fragmentation, IpV4Fragmentation.None, "IP Fragmentation");
                }
                Assert.AreEqual(ipV4Layer.Fragmentation.GetHashCode(), packet.Ethernet.IpV4.Fragmentation.GetHashCode(), "IP Fragmentation");
                Assert.AreEqual(ipV4Layer.Fragmentation.Options, packet.Ethernet.IpV4.Fragmentation.Options, "IP Fragmentation");
                Assert.AreEqual(ipV4Layer.Fragmentation.Offset, packet.Ethernet.IpV4.Fragmentation.Offset, "IP Fragmentation");
                if (ipV4Layer.Fragmentation.Equals(IpV4Fragmentation.None))
                {
                    Assert.AreEqual(IpV4FragmentationOptions.None, packet.Ethernet.IpV4.Fragmentation.Options, "IP Fragmentation");
                    Assert.AreEqual(0, packet.Ethernet.IpV4.Fragmentation.Offset, "IP Fragmentation");
                }
                Assert.AreEqual(true, packet.Ethernet.IpV4.IsHeaderChecksumCorrect, "IP HeaderChecksumCorrect");
                Assert.AreNotEqual(null, packet.Ethernet.IpV4.Options, "IP Options");
                Assert.AreNotEqual(packet.Ethernet.IpV4.Options, null, "IP Options");
                Assert.AreNotEqual(new IpV4Options(new IpV4OptionUnknown(0, new byte[35])), packet.Ethernet.IpV4.Options, "IP Options");
                Assert.AreEqual(ipV4Layer.Options.GetHashCode(), packet.Ethernet.IpV4.Options.GetHashCode(), "IP Options HashCode");
                Assert.IsNotNull(packet.Ethernet.IpV4.Options.ToString());
                for (int optionIndex = 0; optionIndex != ipV4Layer.Options.Count; ++optionIndex)
                {
                    IpV4Option option = ipV4Layer.Options[optionIndex];
                    Assert.AreEqual(option, packet.Ethernet.IpV4.Options[optionIndex]);
                    Assert.IsFalse(option.Equals(null));
                }

                if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp)
                {
                    Assert.IsInstanceOfType(packet.Ethernet.IpV4.Transport, typeof(TcpDatagram));
                }
                else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Udp)
                {
                    Assert.IsInstanceOfType(packet.Ethernet.IpV4.Transport, typeof(UdpDatagram));
                }
                else
                {
                    Assert.IsNull(packet.Ethernet.IpV4.Transport);
                }

                if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Ip)
                {
                    Assert.IsInstanceOfType(packet.Ethernet.IpV4.Ip, typeof(IpV4Datagram));
                }
                else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.IpV6)
                {
                    Assert.IsInstanceOfType(packet.Ethernet.IpV4.Ip, typeof(IpV6Datagram));
                }
                else
                {
                    Assert.IsNull(packet.Ethernet.IpV4.Ip);
                }

                Assert.AreEqual(payloadLayer.Data, packet.Ethernet.IpV4.Payload, "IP Payload");
            }
        }
Example #25
0
        internal static void WriteHeader(byte[] buffer, int offset,
                                         byte recursionControl, byte flags, GreVersion version, EthernetType protocolType,
                                         bool checksumPresent, uint?key, uint?sequenceNumber, uint?acknowledgmentSequenceNumber,
                                         ReadOnlyCollection <GreSourceRouteEntry> routing, ushort?routingOffset, bool strictSourceRoute)
        {
            buffer.Write(offset + Offset.ChecksumPresent,
                         (byte)((checksumPresent ? Mask.ChecksumPresent : 0) |
                                (routing != null ? Mask.RoutingPresent : 0) |
                                (key != null ? Mask.KeyPresent : 0) |
                                (sequenceNumber != null ? Mask.SequenceNumberPresent : 0) |
                                (strictSourceRoute ? Mask.StrictSourceRoute : 0) |
                                (recursionControl & Mask.RecursionControl)));

            buffer.Write(offset + Offset.FutureUseBits, (byte)((acknowledgmentSequenceNumber != null ? Mask.AcknowledgmentSequenceNumberPresent : 0) |
                                                               ((flags << Shift.FutureUseBits) & Mask.FutureUseBits) |
                                                               ((byte)version & Mask.Version)));

            buffer.Write(offset + Offset.ProtocolType, (ushort)protocolType, Endianity.Big);

            offset += Offset.Checksum;
            if (checksumPresent || routing != null)
            {
                offset += sizeof(ushort);
                if (routingOffset != null)
                {
                    buffer.Write(offset, routingOffset.Value, Endianity.Big);
                }
                offset += sizeof(ushort);
            }

            if (key != null)
            {
                buffer.Write(ref offset, key.Value, Endianity.Big);
            }

            if (sequenceNumber != null)
            {
                buffer.Write(ref offset, sequenceNumber.Value, Endianity.Big);
            }

            if (acknowledgmentSequenceNumber != null)
            {
                buffer.Write(ref offset, acknowledgmentSequenceNumber.Value, Endianity.Big);
            }

            if (routing != null)
            {
                foreach (GreSourceRouteEntry entry in routing)
                {
                    entry.Write(buffer, ref offset);
                }

                buffer.Write(ref offset, (uint)0, Endianity.Big);
            }
        }
Example #26
0
        public static GreLayer NextGreLayer(this Random random)
        {
            GreVersion version = random.NextEnum <GreVersion>();

            bool isChecksum = random.NextBool();

            GreSourceRouteEntry[] routing  = null;
            ushort?      routingOffset     = null;
            bool         strictSourceRoute = false;
            EthernetType protocolType      = random.NextEnum(EthernetType.None);
            uint?        key = random.NextBool() ? (uint?)random.NextUInt() : null;

            if (version == GreVersion.Gre)
            {
                if (random.NextBool())
                {
                    strictSourceRoute = random.NextBool();
                    routing           = new GreSourceRouteEntry[random.Next(5)];

                    GreSourceRouteEntryAddressFamily family;
                    if (random.NextBool())
                    {
                        family = random.NextEnum(GreSourceRouteEntryAddressFamily.None);
                    }
                    else
                    {
                        family = (GreSourceRouteEntryAddressFamily)random.NextUShort();
                    }

                    for (int i = 0; i != routing.Length; ++i)
                    {
                        switch (family)
                        {
                        case GreSourceRouteEntryAddressFamily.AsSourceRoute:
                        {
                            ushort[] asNumbers = ((Func <ushort>)(() => random.NextUShort())).GenerateArray(random.NextInt(1, 5));
                            routing[i] = new GreSourceRouteEntryAs(asNumbers.AsReadOnly(), random.Next(asNumbers.Length + 1));
                            break;
                        }

                        case GreSourceRouteEntryAddressFamily.IpSourceRoute:
                        {
                            IpV4Address[] ips = ((Func <IpV4Address>)(() => random.NextIpV4Address())).GenerateArray(random.NextInt(1, 5));
                            routing[i] = new GreSourceRouteEntryIp(ips.AsReadOnly(), random.Next(ips.Length + 1));
                            break;
                        }

                        default:
                        {
                            int dataLength = random.NextInt(1, 100);
                            routing[i] = new GreSourceRouteEntryUnknown(family, random.NextDatagram(dataLength), random.Next(dataLength + 1));
                            break;
                        }
                        }
                    }
                    routingOffset = 0;
                    if (routing.Any())
                    {
                        int routingIndex = random.Next(routing.Length);
                        for (int i = 0; i != routingIndex; ++i)
                        {
                            routingOffset += (ushort)routing[i].Length;
                        }
                    }
                }
            }
            else
            {
                protocolType = EthernetType.PointToPointProtocol;
                isChecksum   = false;
                key          = random.NextUInt();
            }

            return(new GreLayer
            {
                Version = version,
                ProtocolType = protocolType,
                ChecksumPresent = isChecksum,
                Checksum = isChecksum && random.NextBool() ? (ushort?)random.NextUShort() : null,
                Key = key,
                SequenceNumber = random.NextBool() ? (uint?)random.NextUInt() : null,
                AcknowledgmentSequenceNumber = version == GreVersion.EnhancedGre && random.NextBool() ? (uint?)random.NextUInt() : null,
                RecursionControl = random.NextByte(8),
//                       Flags = random.NextByte(32),
                Routing = routing == null ? null : routing.AsReadOnly(),
                RoutingOffset = routingOffset,
                StrictSourceRoute = strictSourceRoute,
            });
        }
Example #27
0
 internal static void WriteHeader(byte[] buffer, int offset, MacAddress ethernetSource, MacAddress ethernetDestination, EthernetType ethernetType)
 {
     buffer.Write(offset + Offset.Source, ethernetSource, Endianity.Big);
     buffer.Write(offset + Offset.Destination, ethernetDestination, Endianity.Big);
     buffer.Write(offset + Offset.EtherTypeLength, (ushort)ethernetType, Endianity.Big);
 }
Example #28
0
        internal static void WriteHeader(byte[] buffer, int offset, ClassOfService priorityCodePoint, bool canonicalFormatIndicator, ushort vLanIdentifier, EthernetType etherType)
        {
            ushort num = VLanTaggedFrameDatagram.CalculateTagControlInformation(priorityCodePoint, canonicalFormatIndicator, vLanIdentifier);

            ByteArrayExtensions.Write(buffer, offset, num, Endianity.Big);
            ByteArrayExtensions.Write(buffer, offset + 2, (ushort)etherType, Endianity.Big);
        }
 public static VLanTaggedFrameLayer NextVLanTaggedFrameLayer(this Random random, EthernetType etherType)
 {
     return(new VLanTaggedFrameLayer
     {
         PriorityCodePoint = random.NextEnum <ClassOfService>(),
         CanonicalFormatIndicator = random.NextBool(),
         VLanIdentifier = random.NextUShort(VLanTaggedFrameDatagram.MaxVLanIdentifier + 1),
         EtherType = etherType,
     });
 }
Example #30
0
 internal static void WriteHeader(byte[] buffer, int offset, MacAddress ethernetSource, MacAddress ethernetDestination, EthernetType ethernetType)
 {
     buffer.Write(offset + Offset.Source, ethernetSource, Endianity.Big);
     buffer.Write(offset + Offset.Destination, ethernetDestination, Endianity.Big);
     buffer.Write(offset + Offset.EtherTypeLength, (ushort)ethernetType, Endianity.Big);
 }
Example #31
0
        /// <summary>
        /// Writes the layer to the buffer.
        /// </summary>
        /// <param name="buffer">The buffer to write the layer to.</param>
        /// <param name="offset">The offset in the buffer to start writing the layer at.</param>
        /// <param name="payloadLength">The length of the layer's payload (the number of bytes after the layer in the packet).</param>
        /// <param name="previousLayer">The layer that comes before this layer. null if this is the first layer.</param>
        /// <param name="nextLayer">The layer that comes after this layer. null if this is the last layer.</param>
        public override void Write(byte[] buffer, int offset, int payloadLength, ILayer previousLayer, ILayer nextLayer)
        {
            EthernetType etherType = GetEthernetType(EtherType, nextLayer);

            VLanTaggedFrameDatagram.WriteHeader(buffer, offset, PriorityCodePoint, CanonicalFormatIndicator, VLanIdentifier, etherType);
        }
Example #32
0
        internal static void WriteHeader(byte[] buffer, int offset, ClassOfService priorityCodePoint, bool canonicalFormatIndicator, ushort vLanIdentifier, EthernetType etherType)
        {
            ushort tagControlInformation = CalculateTagControlInformation(priorityCodePoint, canonicalFormatIndicator, vLanIdentifier);

            buffer.Write(offset + Offset.PriorityCodePoint, tagControlInformation, Endianity.Big);
            buffer.Write(offset + Offset.EtherTypeLength, (ushort)etherType, Endianity.Big);
        }
Example #33
0
 internal static void WriteHeader(byte[] buffer, int offset, ArpHardwareType hardwareType, EthernetType protocolType, ArpOperation operation, IList <byte> senderHardwareAddress, IList <byte> senderProtocolAddress, IList <byte> targetHardwareAddress, IList <byte> targetProtocolAddress)
 {
     ByteArrayExtensions.Write(buffer, ref offset, (ushort)hardwareType, Endianity.Big);
     ByteArrayExtensions.Write(buffer, ref offset, (ushort)protocolType, Endianity.Big);
     ByteArrayExtensions.Write(buffer, ref offset, (byte)senderHardwareAddress.Count);
     ByteArrayExtensions.Write(buffer, ref offset, (byte)senderProtocolAddress.Count);
     ByteArrayExtensions.Write(buffer, ref offset, (ushort)operation, Endianity.Big);
     ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable <byte>)senderHardwareAddress);
     ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable <byte>)senderProtocolAddress);
     ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable <byte>)targetHardwareAddress);
     ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable <byte>)targetProtocolAddress);
 }
Example #34
0
        internal static void WriteHeader(byte[] buffer, int offset,
            byte recursionControl, byte flags, GreVersion version, EthernetType protocolType,
            bool checksumPresent, uint? key, uint? sequenceNumber, uint? acknowledgmentSequenceNumber,
            ReadOnlyCollection<GreSourceRouteEntry> routing, ushort? routingOffset, bool strictSourceRoute)
        {
            buffer.Write(offset + Offset.ChecksumPresent,
                         (byte)((checksumPresent ? Mask.ChecksumPresent : 0) |
                                (routing != null ? Mask.RoutingPresent : 0) |
                                (key != null ? Mask.KeyPresent : 0) |
                                (sequenceNumber != null ? Mask.SequenceNumberPresent : 0) |
                                (strictSourceRoute ? Mask.StrictSourceRoute : 0) |
                                (recursionControl & Mask.RecursionControl)));

            buffer.Write(offset + Offset.FutureUseBits, (byte)((acknowledgmentSequenceNumber != null ? Mask.AcknowledgmentSequenceNumberPresent : 0) |
                                                       ((flags << Shift.FutureUseBits) & Mask.FutureUseBits) |
                                                       ((byte)version & Mask.Version)));

            buffer.Write(offset + Offset.ProtocolType, (ushort)protocolType, Endianity.Big);

            offset += Offset.Checksum;
            if (checksumPresent || routing != null)
            {
                offset += sizeof(ushort);
                if (routingOffset != null)
                    buffer.Write(offset, routingOffset.Value, Endianity.Big);
                offset += sizeof(ushort);
            }

            if (key != null)
                buffer.Write(ref offset, key.Value, Endianity.Big);

            if (sequenceNumber != null)
                buffer.Write(ref offset, sequenceNumber.Value, Endianity.Big);

            if (acknowledgmentSequenceNumber != null)
                buffer.Write(ref offset, acknowledgmentSequenceNumber.Value, Endianity.Big);

            if (routing != null)
            {
                foreach (GreSourceRouteEntry entry in routing)
                    entry.Write(buffer, ref offset);

                buffer.Write(ref offset, (uint)0, Endianity.Big);
            }
        }