public void TestChecksums() { IPPacket.IPVersions[] versions = { IPPacket.IPVersions.IPv4, IPPacket.IPVersions.IPv6 }; for (int i = 0; i < 10000; i++) { int len; //choose random version IPPacket.IPVersions ipver = versions[Rand.Instance.GetInt(0, 1)]; //choose random len based on version if (ipver == IPPacket.IPVersions.IPv4) { len = Rand.Instance.GetInt(54, 1500); } else { len = Rand.Instance.GetInt(74, 1500); } TCPPacket tcp = TCPPacket.RandomPacket(len, ipver); //TODO: this test should use a known quantity, a packet recorded and loaded from a file Assert.AreEqual(len, tcp.Bytes.Length); Assert.IsTrue(tcp.ValidIPChecksum); Assert.IsTrue(tcp.ValidTCPChecksum); } }
/// <summary> Extract the protocol code from packet data. The packet data /// must contain an IP datagram. /// The protocol code specifies what kind of information is contained in the /// data block of the ip datagram. /// /// </summary> /// <param name="lLen">the length of the link-level header. /// </param> /// <param name="packetBytes">packet bytes, including the link-layer header. /// </param> /// <returns> the IP protocol code. i.e. 0x06 signifies TCP protocol. /// </returns> public static int extractProtocol(int lLen, byte[] packetBytes) { IPPacket.IPVersions ipVer = ExtractVersion(lLen, packetBytes); int protoOffset; switch (ipVer) { case IPPacket.IPVersions.IPv4: protoOffset = IPv4Fields_Fields.IP_CODE_POS; break; case IPPacket.IPVersions.IPv6: protoOffset = IPv6Fields_Fields.NEXT_HEADER_POS; break; default: return(-1); //unknown ip version } return(packetBytes[lLen + protoOffset]); }