Commit 98d30c1c authored by Brickner_cp's avatar Brickner_cp

Refactoring

parent 4ee12458
...@@ -3,8 +3,9 @@ ...@@ -3,8 +3,9 @@
<Description>This is a default test run configuration for a local test run.</Description> <Description>This is a default test run configuration for a local test run.</Description>
<CodeCoverage enabled="true" keyFile="PcapDotNet.snk"> <CodeCoverage enabled="true" keyFile="PcapDotNet.snk">
<Regular> <Regular>
<CodeCoverageItem binaryFile="C:\Documents and Settings\Boaz\My Documents\TFS\tfs06.codeplex.com\PcapDotNet\PcapDotNet\bin\Debug\Packets.dll" pdbFile="C:\Documents and Settings\Boaz\My Documents\TFS\tfs06.codeplex.com\PcapDotNet\PcapDotNet\bin\Debug\Packets.pdb" instrumentInPlace="true" /> <CodeCoverageItem binaryFile="C:\TFS\tfs06.codeplex.com\PcapDotNet\PcapDotNet\bin\Debug\PcapDotNet.Base.dll" pdbFile="C:\TFS\tfs06.codeplex.com\PcapDotNet\PcapDotNet\bin\Debug\PcapDotNet.Base.pdb" instrumentInPlace="true" />
<CodeCoverageItem binaryFile="c:\Documents and Settings\Boaz\My Documents\TFS\tfs06.codeplex.com\PcapDotNet\PcapDotNet\bin\Debug\PcapDotNet.Core.dll" pdbFile="c:\Documents and Settings\Boaz\My Documents\TFS\tfs06.codeplex.com\PcapDotNet\PcapDotNet\bin\Debug\PcapDotNet.Core.pdb" instrumentInPlace="true" /> <CodeCoverageItem binaryFile="c:\TFS\tfs06.codeplex.com\PcapDotNet\PcapDotNet\bin\Debug\PcapDotNet.Core.dll" pdbFile="c:\TFS\tfs06.codeplex.com\PcapDotNet\PcapDotNet\bin\Debug\PcapDotNet.Core.pdb" instrumentInPlace="true" />
<CodeCoverageItem binaryFile="C:\TFS\tfs06.codeplex.com\PcapDotNet\PcapDotNet\bin\Debug\PcapDotNet.Packets.dll" pdbFile="C:\TFS\tfs06.codeplex.com\PcapDotNet\PcapDotNet\bin\Debug\PcapDotNet.Packets.pdb" instrumentInPlace="true" />
</Regular> </Regular>
</CodeCoverage> </CodeCoverage>
<TestTypeSpecific> <TestTypeSpecific>
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
<PLACE_CONSTRUCTOR_INITIALIZER_ON_SAME_LINE>False</PLACE_CONSTRUCTOR_INITIALIZER_ON_SAME_LINE> <PLACE_CONSTRUCTOR_INITIALIZER_ON_SAME_LINE>False</PLACE_CONSTRUCTOR_INITIALIZER_ON_SAME_LINE>
<SPACE_AFTER_TYPECAST_PARENTHESES>False</SPACE_AFTER_TYPECAST_PARENTHESES> <SPACE_AFTER_TYPECAST_PARENTHESES>False</SPACE_AFTER_TYPECAST_PARENTHESES>
<SPACE_AROUND_MULTIPLICATIVE_OP>True</SPACE_AROUND_MULTIPLICATIVE_OP> <SPACE_AROUND_MULTIPLICATIVE_OP>True</SPACE_AROUND_MULTIPLICATIVE_OP>
<SPACE_BEFORE_SIZEOF_PARENTHESES>False</SPACE_BEFORE_SIZEOF_PARENTHESES>
<SPACE_BEFORE_TYPEOF_PARENTHESES>False</SPACE_BEFORE_TYPEOF_PARENTHESES> <SPACE_BEFORE_TYPEOF_PARENTHESES>False</SPACE_BEFORE_TYPEOF_PARENTHESES>
<WRAP_LIMIT>150</WRAP_LIMIT> <WRAP_LIMIT>150</WRAP_LIMIT>
</FormatSettings> </FormatSettings>
......
...@@ -59,6 +59,7 @@ ...@@ -59,6 +59,7 @@
<Compile Include="Tuple.cs" /> <Compile Include="Tuple.cs" />
<Compile Include="UInt24.cs" /> <Compile Include="UInt24.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UInt48.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="..\PcapDotNet.snk" /> <None Include="..\PcapDotNet.snk" />
......
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.InteropServices;
using System.Text; using System.Text;
namespace PcapDotNet.Base namespace PcapDotNet.Base
{ {
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct UInt24 public struct UInt24
{ {
public const int SizeOf = 3;
public static readonly UInt24 MaxValue = (UInt24)0x00FFFFFF; public static readonly UInt24 MaxValue = (UInt24)0x00FFFFFF;
private UInt24(int value)
{
_mostSignificant = (ushort)(value >> 8);
_leastSignificant = (byte)value;
}
public static explicit operator UInt24(int value) public static explicit operator UInt24(int value)
{ {
return new UInt24(value); return new UInt24(value);
...@@ -57,12 +54,18 @@ namespace PcapDotNet.Base ...@@ -57,12 +54,18 @@ namespace PcapDotNet.Base
return ((int)this).ToString(); return ((int)this).ToString();
} }
private UInt24(int value)
{
_mostSignificant = (byte)(value >> 16);
_leastSignificant = (ushort)value;
}
private int ToInt() private int ToInt()
{ {
return (_mostSignificant << 8) + _leastSignificant; return (_mostSignificant << 16) + _leastSignificant;
} }
private readonly ushort _mostSignificant; private readonly ushort _leastSignificant;
private readonly byte _leastSignificant; private readonly byte _mostSignificant;
} }
} }
using System.Runtime.InteropServices;
namespace PcapDotNet.Base
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct UInt48
{
public const int SizeOf = 6;
public static readonly UInt48 MaxValue = (UInt48)0x0000FFFFFFFFFFFF;
public static explicit operator UInt48(long value)
{
return new UInt48(value);
}
public static implicit operator long(UInt48 value)
{
return value.ToLong();
}
public bool Equals(UInt48 other)
{
return _mostSignificant == other._mostSignificant &&
_leastSignificant == other._leastSignificant;
}
public override bool Equals(object obj)
{
return (obj is UInt48) &&
Equals((UInt48)obj);
}
public static bool operator ==(UInt48 value1, UInt48 value2)
{
return value1.Equals(value2);
}
public static bool operator !=(UInt48 value1, UInt48 value2)
{
return !(value1 == value2);
}
public override int GetHashCode()
{
return ((long)this).GetHashCode();
}
public override string ToString()
{
return ((long)this).ToString();
}
private UInt48(long value)
{
_mostSignificant = (ushort)(value >> 32);
_leastSignificant = (uint)value;
}
private long ToLong()
{
return (((long)_mostSignificant) << 32) + _leastSignificant;
}
private readonly uint _leastSignificant;
private readonly ushort _mostSignificant;
}
}
\ No newline at end of file
using System; using System;
using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.TestTools.UnitTesting;
using PcapDotNet.Packets; using PcapDotNet.Packets;
using PcapDotNet.Packets.TestUtils;
namespace PcapDotNet.Core.Test namespace PcapDotNet.Core.Test
{ {
...@@ -73,8 +74,9 @@ namespace PcapDotNet.Core.Test ...@@ -73,8 +74,9 @@ namespace PcapDotNet.Core.Test
const string SourceMac = "11:22:33:44:55:66"; const string SourceMac = "11:22:33:44:55:66";
const string DestinationMac = "77:88:99:AA:BB:CC"; const string DestinationMac = "77:88:99:AA:BB:CC";
Packet expectedPacket = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, 1000); Random random = new Random();
Packet unexpectedPacket = MoreRandom.BuildRandomPacket(DestinationMac, SourceMac, 1000); Packet expectedPacket = random.NextEthernet(1000, SourceMac, DestinationMac);
Packet unexpectedPacket = random.NextEthernet(1000, DestinationMac, SourceMac);
using (BerkeleyPacketFilter filter = new BerkeleyPacketFilter("ether src " + SourceMac + " and ether dst " + DestinationMac, 1000, DataLinkKind.Ethernet)) using (BerkeleyPacketFilter filter = new BerkeleyPacketFilter("ether src " + SourceMac + " and ether dst " + DestinationMac, 1000, DataLinkKind.Ethernet))
{ {
...@@ -91,8 +93,9 @@ namespace PcapDotNet.Core.Test ...@@ -91,8 +93,9 @@ namespace PcapDotNet.Core.Test
const string SourceMac = "11:22:33:44:55:66"; const string SourceMac = "11:22:33:44:55:66";
const string DestinationMac = "77:88:99:AA:BB:CC"; const string DestinationMac = "77:88:99:AA:BB:CC";
Packet expectedPacket = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, 1000); Random random = new Random();
Packet unexpectedPacket = MoreRandom.BuildRandomPacket(DestinationMac, SourceMac, 1000); Packet expectedPacket = random.NextEthernet(1000, SourceMac, DestinationMac);
Packet unexpectedPacket = random.NextEthernet(1000, DestinationMac, SourceMac);
using (PacketCommunicator communicator = LivePacketDeviceTests.OpenLiveDevice()) using (PacketCommunicator communicator = LivePacketDeviceTests.OpenLiveDevice())
{ {
...@@ -110,19 +113,20 @@ namespace PcapDotNet.Core.Test ...@@ -110,19 +113,20 @@ namespace PcapDotNet.Core.Test
const string DestinationMac = "77:88:99:AA:BB:CC"; const string DestinationMac = "77:88:99:AA:BB:CC";
const int snapshotLength = 500; const int snapshotLength = 500;
Random random = new Random();
using (BerkeleyPacketFilter filter = new BerkeleyPacketFilter("ether src " + SourceMac + " and ether dst " + DestinationMac, snapshotLength, DataLinkKind.Ethernet)) using (BerkeleyPacketFilter filter = new BerkeleyPacketFilter("ether src " + SourceMac + " and ether dst " + DestinationMac, snapshotLength, DataLinkKind.Ethernet))
{ {
Assert.IsTrue(filter.Test(MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, snapshotLength / 2))); Assert.IsTrue(filter.Test(random.NextEthernet(snapshotLength / 2, SourceMac, DestinationMac)));
Assert.IsTrue(filter.Test(MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, snapshotLength - 1))); Assert.IsTrue(filter.Test(random.NextEthernet(snapshotLength - 1, SourceMac, DestinationMac)));
Assert.IsTrue(filter.Test(MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, snapshotLength))); Assert.IsTrue(filter.Test(random.NextEthernet(snapshotLength, SourceMac, DestinationMac)));
Assert.IsTrue(filter.Test(MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, snapshotLength + 1))); Assert.IsTrue(filter.Test(random.NextEthernet(snapshotLength + 1, SourceMac, DestinationMac)));
Assert.IsTrue(filter.Test(MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, snapshotLength / 2))); Assert.IsTrue(filter.Test(random.NextEthernet(snapshotLength * 2, SourceMac, DestinationMac)));
Assert.IsFalse(filter.Test(MoreRandom.BuildRandomPacket(DestinationMac, SourceMac, snapshotLength / 2))); Assert.IsFalse(filter.Test(random.NextEthernet(snapshotLength / 2, DestinationMac, SourceMac)));
int actualSnapshotLength; int actualSnapshotLength;
Assert.IsTrue(filter.Test(out actualSnapshotLength, MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, snapshotLength / 2))); Assert.IsTrue(filter.Test(out actualSnapshotLength, random.NextEthernet(snapshotLength / 2, SourceMac, DestinationMac)));
Assert.AreEqual(snapshotLength, actualSnapshotLength); Assert.AreEqual(snapshotLength, actualSnapshotLength);
} }
} }
......
using System; using System;
using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.TestTools.UnitTesting;
using PcapDotNet.Base;
using PcapDotNet.Packets; using PcapDotNet.Packets;
using PcapDotNet.Packets.TestUtils; using PcapDotNet.Packets.TestUtils;
using PcapDotNet.TestUtils; using PcapDotNet.TestUtils;
...@@ -68,9 +69,9 @@ namespace PcapDotNet.Core.Test ...@@ -68,9 +69,9 @@ namespace PcapDotNet.Core.Test
Random random = new Random(); Random random = new Random();
/*
using (PacketCommunicator communicator = LivePacketDeviceTests.OpenLiveDevice()) using (PacketCommunicator communicator = LivePacketDeviceTests.OpenLiveDevice())
{ {
/*
using (PacketDumpFile dumpFile = communicator.OpenDump(@"c:\wow.pcap")) using (PacketDumpFile dumpFile = communicator.OpenDump(@"c:\wow.pcap"))
{ {
for (int i = 0; i != 1000; ++i) for (int i = 0; i != 1000; ++i)
...@@ -91,17 +92,17 @@ namespace PcapDotNet.Core.Test ...@@ -91,17 +92,17 @@ namespace PcapDotNet.Core.Test
Datagram ipV4Payload = new Datagram(ipV4PayloadBuffer); Datagram ipV4Payload = new Datagram(ipV4PayloadBuffer);
Packet packet = PacketBuilder.EthernetIpV4(DateTime.Now, Packet packet = PacketBuilder.EthernetIpV4(DateTime.Now,
ethernetSource, ethernetDestination, ethernetType, ethernetSource, ethernetDestination, ethernetType,
ipV4TypeOfService, ipV4Identification, ipV4Fragmentation, ipV4Ttl, ipV4Protocol, ipV4TypeOfService, ipV4Identification, ipV4Fragmentation, ipV4Ttl, ipV4Protocol,
ipV4Source, ipV4Destination, ipV4Options, ipV4Source, ipV4Destination, ipV4Options,
ipV4Payload); ipV4Payload);
dumpFile.Dump(packet); dumpFile.Dump(packet);
dumpFile.Flush(); dumpFile.Flush();
} }
} }
*/
} }
*/
} }
} }
} }
\ No newline at end of file
...@@ -6,6 +6,7 @@ using System.Text.RegularExpressions; ...@@ -6,6 +6,7 @@ using System.Text.RegularExpressions;
using System.Threading; using System.Threading;
using PcapDotNet.Packets; using PcapDotNet.Packets;
using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.TestTools.UnitTesting;
using PcapDotNet.Packets.TestUtils;
namespace PcapDotNet.Core.Test namespace PcapDotNet.Core.Test
{ {
...@@ -82,7 +83,7 @@ namespace PcapDotNet.Core.Test ...@@ -82,7 +83,7 @@ namespace PcapDotNet.Core.Test
Assert.AreEqual<uint>(0, communicator.TotalStatistics.PacketsCaptured); Assert.AreEqual<uint>(0, communicator.TotalStatistics.PacketsCaptured);
MoreAssert.IsInRange(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1.02), finishedWaiting - startWaiting); MoreAssert.IsInRange(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1.02), finishedWaiting - startWaiting);
Packet sentPacket = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, 24); Packet sentPacket = _random.NextEthernet(24, SourceMac, DestinationMac);
DateTime startSendingTime = DateTime.Now; DateTime startSendingTime = DateTime.Now;
...@@ -146,6 +147,7 @@ namespace PcapDotNet.Core.Test ...@@ -146,6 +147,7 @@ namespace PcapDotNet.Core.Test
} }
[TestMethod] [TestMethod]
[Timeout(10 * 1000)]
public void ReceivePacketsGcCollectTest() public void ReceivePacketsGcCollectTest()
{ {
const string SourceMac = "11:22:33:44:55:66"; const string SourceMac = "11:22:33:44:55:66";
...@@ -157,7 +159,7 @@ namespace PcapDotNet.Core.Test ...@@ -157,7 +159,7 @@ namespace PcapDotNet.Core.Test
{ {
communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac); communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);
Packet sentPacket = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, 100); Packet sentPacket = _random.NextEthernet(100, SourceMac, DestinationMac);
for (int i = 0; i != NumPackets; ++i) for (int i = 0; i != NumPackets; ++i)
communicator.SendPacket(sentPacket); communicator.SendPacket(sentPacket);
...@@ -182,7 +184,7 @@ namespace PcapDotNet.Core.Test ...@@ -182,7 +184,7 @@ namespace PcapDotNet.Core.Test
{ {
communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac); communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);
Packet sentPacket = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, 100); Packet sentPacket = _random.NextEthernet(100, SourceMac, DestinationMac);
for (int i = 0; i != NumPackets; ++i) for (int i = 0; i != NumPackets; ++i)
communicator.SendPacket(sentPacket); communicator.SendPacket(sentPacket);
...@@ -232,7 +234,7 @@ namespace PcapDotNet.Core.Test ...@@ -232,7 +234,7 @@ namespace PcapDotNet.Core.Test
communicator.Mode = PacketCommunicatorMode.Statistics; communicator.Mode = PacketCommunicatorMode.Statistics;
communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac); communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);
Packet sentPacket = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, PacketSize); Packet sentPacket = _random.NextEthernet(PacketSize, SourceMac, DestinationMac);
PacketSampleStatistics statistics; PacketSampleStatistics statistics;
PacketCommunicatorReceiveResult result = communicator.ReceiveStatistics(out statistics); PacketCommunicatorReceiveResult result = communicator.ReceiveStatistics(out statistics);
...@@ -339,7 +341,7 @@ namespace PcapDotNet.Core.Test ...@@ -339,7 +341,7 @@ namespace PcapDotNet.Core.Test
{ {
communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac); communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);
communicator.SetKernelBufferSize(50); communicator.SetKernelBufferSize(50);
Packet packet = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, 100); Packet packet = _random.NextEthernet(100, SourceMac, DestinationMac);
communicator.SendPacket(packet); communicator.SendPacket(packet);
communicator.ReceivePacket(out packet); communicator.ReceivePacket(out packet);
} }
...@@ -356,7 +358,7 @@ namespace PcapDotNet.Core.Test ...@@ -356,7 +358,7 @@ namespace PcapDotNet.Core.Test
{ {
communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac); communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);
communicator.SetKernelBufferSize(50); communicator.SetKernelBufferSize(50);
Packet packet = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, 100); Packet packet = _random.NextEthernet(100, SourceMac, DestinationMac);
communicator.SendPacket(packet); communicator.SendPacket(packet);
int numPacketsGot; int numPacketsGot;
communicator.ReceiveSomePackets(out numPacketsGot, 1, delegate { }); communicator.ReceiveSomePackets(out numPacketsGot, 1, delegate { });
...@@ -374,7 +376,7 @@ namespace PcapDotNet.Core.Test ...@@ -374,7 +376,7 @@ namespace PcapDotNet.Core.Test
{ {
communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac); communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);
communicator.SetKernelBufferSize(50); communicator.SetKernelBufferSize(50);
Packet packet = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, 100); Packet packet = _random.NextEthernet(100, SourceMac, DestinationMac);
communicator.SendPacket(packet); communicator.SendPacket(packet);
Exception exception = null; Exception exception = null;
Thread thread = new Thread(delegate() Thread thread = new Thread(delegate()
...@@ -432,7 +434,7 @@ namespace PcapDotNet.Core.Test ...@@ -432,7 +434,7 @@ namespace PcapDotNet.Core.Test
{ {
communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac); communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);
communicator.SetKernelMinimumBytesToCopy(1024 * 1024); communicator.SetKernelMinimumBytesToCopy(1024 * 1024);
Packet expectedPacket = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, 100); Packet expectedPacket = _random.NextEthernet(100, SourceMac, DestinationMac);
for (int i = 0; i != 5; ++i) for (int i = 0; i != 5; ++i)
{ {
communicator.SendPacket(expectedPacket); communicator.SendPacket(expectedPacket);
...@@ -457,7 +459,7 @@ namespace PcapDotNet.Core.Test ...@@ -457,7 +459,7 @@ namespace PcapDotNet.Core.Test
{ {
communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac); communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);
communicator.SetKernelMinimumBytesToCopy(1); communicator.SetKernelMinimumBytesToCopy(1);
Packet expectedPacket = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, 100); Packet expectedPacket = _random.NextEthernet(100, SourceMac, DestinationMac);
for (int i = 0; i != 100; ++i) for (int i = 0; i != 100; ++i)
{ {
communicator.SendPacket(expectedPacket); communicator.SendPacket(expectedPacket);
...@@ -484,7 +486,7 @@ namespace PcapDotNet.Core.Test ...@@ -484,7 +486,7 @@ namespace PcapDotNet.Core.Test
communicator.SetSamplingMethod(new SamplingMethodOneEveryCount(5)); communicator.SetSamplingMethod(new SamplingMethodOneEveryCount(5));
for (int i = 0; i != 20; ++i) for (int i = 0; i != 20; ++i)
{ {
Packet expectedPacket = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, 60 * (i + 1)); Packet expectedPacket = _random.NextEthernet(60 * (i + 1), SourceMac, DestinationMac);
communicator.SendPacket(expectedPacket); communicator.SendPacket(expectedPacket);
} }
...@@ -512,12 +514,12 @@ namespace PcapDotNet.Core.Test ...@@ -512,12 +514,12 @@ namespace PcapDotNet.Core.Test
{ {
communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac); communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);
communicator.SetSamplingMethod(new SamplingMethodFirstAfterInterval(TimeSpan.FromSeconds(1))); communicator.SetSamplingMethod(new SamplingMethodFirstAfterInterval(TimeSpan.FromSeconds(1)));
Packet expectedPacket = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, 60); Packet expectedPacket = _random.NextEthernet(60, SourceMac, DestinationMac);
communicator.SendPacket(expectedPacket); communicator.SendPacket(expectedPacket);
Thread.Sleep(TimeSpan.FromSeconds(0.75)); Thread.Sleep(TimeSpan.FromSeconds(0.75));
for (int i = 0; i != 10; ++i) for (int i = 0; i != 10; ++i)
{ {
expectedPacket = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, 60 * (i + 2)); expectedPacket = _random.NextEthernet(60 * (i + 2), SourceMac, DestinationMac);
communicator.SendPacket(expectedPacket); communicator.SendPacket(expectedPacket);
Thread.Sleep(TimeSpan.FromSeconds(0.5)); Thread.Sleep(TimeSpan.FromSeconds(0.5));
} }
...@@ -585,7 +587,7 @@ namespace PcapDotNet.Core.Test ...@@ -585,7 +587,7 @@ namespace PcapDotNet.Core.Test
communicator.SetFilter("ether src " + sourceMac + " and ether dst " + destinationMac); communicator.SetFilter("ether src " + sourceMac + " and ether dst " + destinationMac);
Packet sentPacket = MoreRandom.BuildRandomPacket(sourceMac, destinationMac, packetSize); Packet sentPacket = _random.NextEthernet(packetSize, sourceMac, destinationMac);
PacketCommunicatorReceiveResult result = PacketCommunicatorReceiveResult.None; PacketCommunicatorReceiveResult result = PacketCommunicatorReceiveResult.None;
int numStatisticsGot = 0; int numStatisticsGot = 0;
...@@ -635,7 +637,7 @@ namespace PcapDotNet.Core.Test ...@@ -635,7 +637,7 @@ namespace PcapDotNet.Core.Test
const string SourceMac = "11:22:33:44:55:66"; const string SourceMac = "11:22:33:44:55:66";
const string DestinationMac = "77:88:99:AA:BB:CC"; const string DestinationMac = "77:88:99:AA:BB:CC";
Packet packetToSend = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, packetSize); Packet packetToSend = _random.NextEthernet(packetSize, SourceMac, DestinationMac);
using (PacketCommunicator communicator = OpenLiveDevice()) using (PacketCommunicator communicator = OpenLiveDevice())
{ {
...@@ -679,7 +681,7 @@ namespace PcapDotNet.Core.Test ...@@ -679,7 +681,7 @@ namespace PcapDotNet.Core.Test
{ {
communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac); communicator.SetFilter("ether src " + SourceMac + " and ether dst " + DestinationMac);
Packet sentPacket = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, packetSize); Packet sentPacket = _random.NextEthernet(packetSize, SourceMac, DestinationMac);
PacketCommunicatorReceiveResult result = PacketCommunicatorReceiveResult.None; PacketCommunicatorReceiveResult result = PacketCommunicatorReceiveResult.None;
...@@ -753,5 +755,7 @@ namespace PcapDotNet.Core.Test ...@@ -753,5 +755,7 @@ namespace PcapDotNet.Core.Test
throw; throw;
} }
} }
private static Random _random = new Random();
} }
} }
\ No newline at end of file
using System;
using PcapDotNet.Packets;
namespace PcapDotNet.Core.Test
{
internal static class MoreRandom
{
public static Packet BuildRandomPacket(DateTime timestamp, string sourceMac, string destinationMac, int packetSize)
{
if (packetSize < EthernetDatagram.HeaderLength)
throw new ArgumentOutOfRangeException("packetSize", packetSize, "Must be at least the ethernet header length (" + EthernetDatagram.HeaderLength + ")");
return PacketBuilder.Ethernet(timestamp,
new MacAddress(sourceMac),
new MacAddress(destinationMac),
EthernetType.IpV4,
GetRandomDatagram(packetSize - EthernetDatagram.HeaderLength));
}
public static Packet BuildRandomPacket(string sourceMac, string destinationMac, int packetSize)
{
return BuildRandomPacket(DateTime.Now, sourceMac, destinationMac, packetSize);
}
public static Packet BuildRandomPacket(int packetSize)
{
return BuildRandomPacket(DateTime.Now, GetRandomMacAddress().ToString(), GetRandomMacAddress().ToString(), packetSize);
}
private static Datagram GetRandomDatagram(int length)
{
byte[] buffer = new byte[length];
_random.NextBytes(buffer);
return new Datagram(buffer);
}
private static MacAddress GetRandomMacAddress()
{
byte[] buffer = new byte[6];
_random.NextBytes(buffer);
return new MacAddress(buffer, 0);
}
private static readonly Random _random = new Random();
}
}
\ No newline at end of file
...@@ -4,6 +4,7 @@ using System.IO; ...@@ -4,6 +4,7 @@ using System.IO;
using System.Threading; using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.TestTools.UnitTesting;
using PcapDotNet.Packets; using PcapDotNet.Packets;
using PcapDotNet.Packets.TestUtils;
namespace PcapDotNet.Core.Test namespace PcapDotNet.Core.Test
{ {
...@@ -67,7 +68,7 @@ namespace PcapDotNet.Core.Test ...@@ -67,7 +68,7 @@ namespace PcapDotNet.Core.Test
const string DestinationMac = "77:88:99:AA:BB:CC"; const string DestinationMac = "77:88:99:AA:BB:CC";
const int NumPackets = 10; const int NumPackets = 10;
Packet expectedPacket = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, 100); Packet expectedPacket = _random.NextEthernet(100, SourceMac, DestinationMac);
using (PacketCommunicator communicator = OpenOfflineDevice(NumPackets, expectedPacket)) using (PacketCommunicator communicator = OpenOfflineDevice(NumPackets, expectedPacket))
{ {
...@@ -176,7 +177,7 @@ namespace PcapDotNet.Core.Test ...@@ -176,7 +177,7 @@ namespace PcapDotNet.Core.Test
{ {
using (PacketCommunicator communicator = OpenOfflineDevice()) using (PacketCommunicator communicator = OpenOfflineDevice())
{ {
communicator.SendPacket(MoreRandom.BuildRandomPacket(100)); communicator.SendPacket(_random.NextEthernet(100));
} }
} }
...@@ -203,7 +204,7 @@ namespace PcapDotNet.Core.Test ...@@ -203,7 +204,7 @@ namespace PcapDotNet.Core.Test
[TestMethod] [TestMethod]
public void SetSamplingMethodOneEveryNTest() public void SetSamplingMethodOneEveryNTest()
{ {
Packet expectedPacket = MoreRandom.BuildRandomPacket(100); Packet expectedPacket = _random.NextEthernet(100);
using (PacketCommunicator communicator = OpenOfflineDevice(101, expectedPacket)) using (PacketCommunicator communicator = OpenOfflineDevice(101, expectedPacket))
{ {
communicator.SetSamplingMethod(new SamplingMethodOneEveryCount(10)); communicator.SetSamplingMethod(new SamplingMethodOneEveryCount(10));
...@@ -226,7 +227,7 @@ namespace PcapDotNet.Core.Test ...@@ -226,7 +227,7 @@ namespace PcapDotNet.Core.Test
{ {
const int NumPackets = 10; const int NumPackets = 10;
Packet expectedPacket = MoreRandom.BuildRandomPacket(100); Packet expectedPacket = _random.NextEthernet(100);
using (PacketCommunicator communicator = OpenOfflineDevice(NumPackets, expectedPacket, TimeSpan.FromSeconds(1))) using (PacketCommunicator communicator = OpenOfflineDevice(NumPackets, expectedPacket, TimeSpan.FromSeconds(1)))
{ {
communicator.SetSamplingMethod(new SamplingMethodFirstAfterInterval(TimeSpan.FromSeconds(2))); communicator.SetSamplingMethod(new SamplingMethodFirstAfterInterval(TimeSpan.FromSeconds(2)));
...@@ -251,7 +252,7 @@ namespace PcapDotNet.Core.Test ...@@ -251,7 +252,7 @@ namespace PcapDotNet.Core.Test
[ExpectedException(typeof(InvalidOperationException))] [ExpectedException(typeof(InvalidOperationException))]
public void DumpToBadFileTest() public void DumpToBadFileTest()
{ {
OpenOfflineDevice(10, MoreRandom.BuildRandomPacket(100), TimeSpan.Zero, "??"); OpenOfflineDevice(10, _random.NextEthernet(100), TimeSpan.Zero, "??");
} }
private static void TestGetSomePackets(int numPacketsToSend, int numPacketsToGet, int numPacketsToBreakLoop, private static void TestGetSomePackets(int numPacketsToSend, int numPacketsToGet, int numPacketsToBreakLoop,
...@@ -264,7 +265,7 @@ namespace PcapDotNet.Core.Test ...@@ -264,7 +265,7 @@ namespace PcapDotNet.Core.Test
const string SourceMac = "11:22:33:44:55:66"; const string SourceMac = "11:22:33:44:55:66";
const string DestinationMac = "77:88:99:AA:BB:CC"; const string DestinationMac = "77:88:99:AA:BB:CC";
Packet expectedPacket = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, 100); Packet expectedPacket = _random.NextEthernet(100, SourceMac, DestinationMac);
using (PacketCommunicator communicator = OpenOfflineDevice(numPacketsToSend, expectedPacket)) using (PacketCommunicator communicator = OpenOfflineDevice(numPacketsToSend, expectedPacket))
{ {
...@@ -292,7 +293,7 @@ namespace PcapDotNet.Core.Test ...@@ -292,7 +293,7 @@ namespace PcapDotNet.Core.Test
const string SourceMac = "11:22:33:44:55:66"; const string SourceMac = "11:22:33:44:55:66";
const string DestinationMac = "77:88:99:AA:BB:CC"; const string DestinationMac = "77:88:99:AA:BB:CC";
Packet expectedPacket = MoreRandom.BuildRandomPacket(SourceMac, DestinationMac, 24); Packet expectedPacket = _random.NextEthernet(24, SourceMac, DestinationMac);
using (PacketCommunicator communicator = OpenOfflineDevice(numPacketsToSend, expectedPacket)) using (PacketCommunicator communicator = OpenOfflineDevice(numPacketsToSend, expectedPacket))
{ {
...@@ -321,7 +322,7 @@ namespace PcapDotNet.Core.Test ...@@ -321,7 +322,7 @@ namespace PcapDotNet.Core.Test
public static PacketCommunicator OpenOfflineDevice() public static PacketCommunicator OpenOfflineDevice()
{ {
return OpenOfflineDevice(10, MoreRandom.BuildRandomPacket(100)); return OpenOfflineDevice(10, _random.NextEthernet(100));
} }
...@@ -384,5 +385,7 @@ namespace PcapDotNet.Core.Test ...@@ -384,5 +385,7 @@ namespace PcapDotNet.Core.Test
throw; throw;
} }
} }
private static Random _random = new Random();
} }
} }
\ No newline at end of file
...@@ -2,6 +2,7 @@ using System; ...@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.TestTools.UnitTesting;
using PcapDotNet.Packets; using PcapDotNet.Packets;
using PcapDotNet.Packets.TestUtils;
namespace PcapDotNet.Core.Test namespace PcapDotNet.Core.Test
{ {
...@@ -148,7 +149,7 @@ namespace PcapDotNet.Core.Test ...@@ -148,7 +149,7 @@ namespace PcapDotNet.Core.Test
packetsToSend = new List<Packet>(numPackets); packetsToSend = new List<Packet>(numPackets);
for (int i = 0; i != numPackets; ++i) for (int i = 0; i != numPackets; ++i)
{ {
Packet packetToSend = MoreRandom.BuildRandomPacket(timestamp, sourceMac, destinationMac, packetSize); Packet packetToSend = _random.NextEthernet(packetSize, timestamp, sourceMac, destinationMac);
queue.Enqueue(packetToSend); queue.Enqueue(packetToSend);
packetsToSend.Add(packetToSend); packetsToSend.Add(packetToSend);
timestamp = timestamp.AddSeconds(secondsBetweenTimestamps); timestamp = timestamp.AddSeconds(secondsBetweenTimestamps);
...@@ -162,5 +163,7 @@ namespace PcapDotNet.Core.Test ...@@ -162,5 +163,7 @@ namespace PcapDotNet.Core.Test
return queue; return queue;
} }
private static Random _random = new Random();
} }
} }
\ No newline at end of file
...@@ -46,7 +46,6 @@ ...@@ -46,7 +46,6 @@
<Compile Include="DumpPacketsTests.cs" /> <Compile Include="DumpPacketsTests.cs" />
<Compile Include="MoreAssert.cs" /> <Compile Include="MoreAssert.cs" />
<Compile Include="LivePacketDeviceTests.cs" /> <Compile Include="LivePacketDeviceTests.cs" />
<Compile Include="MoreRandom.cs" />
<Compile Include="PacketHandler.cs" /> <Compile Include="PacketHandler.cs" />
<Compile Include="OfflinePacketDeviceTests.cs" /> <Compile Include="OfflinePacketDeviceTests.cs" />
<Compile Include="PacketSendBufferTests.cs" /> <Compile Include="PacketSendBufferTests.cs" />
...@@ -55,6 +54,10 @@ ...@@ -55,6 +54,10 @@
<Compile Include="PcapLibTests.cs" /> <Compile Include="PcapLibTests.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\PcapDotNet.Base\PcapDotNet.Base.csproj">
<Project>{83E805C9-4D29-4E34-A27E-5A78690FBD2B}</Project>
<Name>PcapDotNet.Base</Name>
</ProjectReference>
<ProjectReference Include="..\PcapDotNet.Core\WinPCapDotNet.Core.vcproj"> <ProjectReference Include="..\PcapDotNet.Core\WinPCapDotNet.Core.vcproj">
<Project>{89C63BE1-AF9A-472E-B256-A4F56B1655A7}</Project> <Project>{89C63BE1-AF9A-472E-B256-A4F56B1655A7}</Project>
<Name>PcapDotNet.Core</Name> <Name>PcapDotNet.Core</Name>
......
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PcapDotNet.Base;
namespace PcapDotNet.Packets.Test
{
/// <summary>
/// Summary description for EndianitiyTests
/// </summary>
[TestClass]
public class EndianitiyTests
{
public EndianitiyTests()
{
//
// TODO: Add constructor logic here
//
}
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
[TestMethod]
public void UIntTest()
{
const uint value = 0x01020304;
byte[] buffer = new byte[sizeof(uint)];
buffer.Write(0, value, Endianity.Big);
Assert.AreEqual(value, buffer.ReadUInt(0, Endianity.Big));
Assert.AreEqual(0x01, buffer[0]);
Assert.AreEqual(0x02, buffer[1]);
Assert.AreEqual(0x03, buffer[2]);
Assert.AreEqual(0x04, buffer[3]);
buffer.Write(0, value, Endianity.Small);
Assert.AreEqual(value, buffer.ReadUInt(0, Endianity.Small));
Assert.AreEqual(0x04, buffer[0]);
Assert.AreEqual(0x03, buffer[1]);
Assert.AreEqual(0x02, buffer[2]);
Assert.AreEqual(0x01, buffer[3]);
}
[TestMethod]
public void UInt24Test()
{
UInt24 value = (UInt24)0x010203;
byte[] buffer = new byte[UInt24.SizeOf];
buffer.Write(0, value, Endianity.Big);
Assert.AreEqual(value, buffer.ReadUInt24(0, Endianity.Big));
Assert.AreEqual(0x01, buffer[0]);
Assert.AreEqual(0x02, buffer[1]);
Assert.AreEqual(0x03, buffer[2]);
buffer.Write(0, value, Endianity.Small);
Assert.AreEqual(value, buffer.ReadUInt24(0, Endianity.Small));
Assert.AreEqual(0x03, buffer[0]);
Assert.AreEqual(0x02, buffer[1]);
Assert.AreEqual(0x01, buffer[2]);
}
[TestMethod]
public void UInt48Test()
{
UInt48 value = (UInt48)0x010203040506;
byte[] buffer = new byte[UInt48.SizeOf];
buffer.Write(0, value, Endianity.Big);
Assert.AreEqual(value, buffer.ReadUInt48(0, Endianity.Big));
Assert.AreEqual(0x01, buffer[0]);
Assert.AreEqual(0x02, buffer[1]);
Assert.AreEqual(0x03, buffer[2]);
Assert.AreEqual(0x04, buffer[3]);
Assert.AreEqual(0x05, buffer[4]);
Assert.AreEqual(0x06, buffer[5]);
buffer.Write(0, value, Endianity.Small);
Assert.AreEqual(value, buffer.ReadUInt48(0, Endianity.Small));
Assert.AreEqual(0x06, buffer[0]);
Assert.AreEqual(0x05, buffer[1]);
Assert.AreEqual(0x04, buffer[2]);
Assert.AreEqual(0x03, buffer[3]);
Assert.AreEqual(0x02, buffer[4]);
Assert.AreEqual(0x01, buffer[5]);
}
}
}
\ No newline at end of file
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PcapDotNet.Packets.TestUtils;
using PcapDotNet.TestUtils;
namespace PcapDotNet.Packets.Test
{
/// <summary>
/// Summary description for EthernetTests
/// </summary>
[TestClass]
public class EthernetTests
{
public EthernetTests()
{
//
// TODO: Add constructor logic here
//
}
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
[TestMethod]
public void RandomEthernetTest()
{
Random random = new Random();
for (int i = 0; i != 1000; ++i)
{
MacAddress ethernetSource = random.NextMacAddress();
MacAddress ethernetDestination = random.NextMacAddress();
EthernetType ethernetType = random.NextEnum(EthernetType.None);
int ethernetPayloadLength = random.Next(1500);
Datagram ethernetPayload = random.NextDatagram(ethernetPayloadLength);
Packet packet = PacketBuilder.Ethernet(DateTime.Now,
ethernetSource, ethernetDestination, ethernetType,
ethernetPayload);
Assert.IsTrue(packet.IsValid);
// Ethernet
Assert.AreEqual(packet.Length - EthernetDatagram.HeaderLength, packet.Ethernet.PayloadLength, "PayloadLength");
Assert.AreEqual(ethernetSource, packet.Ethernet.Source, "Ethernet Source");
Assert.AreEqual(ethernetDestination, packet.Ethernet.Destination, "Ethernet Destination");
Assert.AreEqual(ethernetType, packet.Ethernet.EtherType, "Ethernet Type");
Assert.AreEqual(ethernetPayload, packet.Ethernet.Payload);
}
}
}
}
\ No newline at end of file
...@@ -94,7 +94,7 @@ namespace PcapDotNet.Packets.Test ...@@ -94,7 +94,7 @@ namespace PcapDotNet.Packets.Test
} }
[TestMethod] [TestMethod]
public void SimplePacketTest() public void RandomIpV4Test()
{ {
MacAddress ethernetSource = new MacAddress("00:01:02:03:04:05"); MacAddress ethernetSource = new MacAddress("00:01:02:03:04:05");
MacAddress ethernetDestination = new MacAddress("A0:A1:A2:A3:A4:A5"); MacAddress ethernetDestination = new MacAddress("A0:A1:A2:A3:A4:A5");
...@@ -114,7 +114,6 @@ namespace PcapDotNet.Packets.Test ...@@ -114,7 +114,6 @@ namespace PcapDotNet.Packets.Test
IpV4Address ipV4Source = new IpV4Address(random.NextUInt()); IpV4Address ipV4Source = new IpV4Address(random.NextUInt());
IpV4Address ipV4Destination = new IpV4Address(random.NextUInt()); IpV4Address ipV4Destination = new IpV4Address(random.NextUInt());
IpV4Options ipV4Options = random.NextIpV4Options(); IpV4Options ipV4Options = random.NextIpV4Options();
// IpV4Options ipV4Options = new IpV4Options(new IpV4OptionSecurity(IpV4OptionSecurityLevel.Unclassified, 1, 2, (UInt24)123456));
byte[] ipV4PayloadBuffer = new byte[random.Next(0, 50 * 1024)]; byte[] ipV4PayloadBuffer = new byte[random.Next(0, 50 * 1024)];
random.NextBytes(ipV4PayloadBuffer); random.NextBytes(ipV4PayloadBuffer);
......
...@@ -4,12 +4,12 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; ...@@ -4,12 +4,12 @@ using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PcapDotNet.Packets.Test namespace PcapDotNet.Packets.Test
{ {
/// <summary> /// <summary>
/// Summary description for EthernetDatagramTests /// Summary description for PacketTests
/// </summary> /// </summary>
[TestClass] [TestClass]
public class EthernetDatagramTests public class PacketTests
{ {
public EthernetDatagramTests() public PacketTests()
{ {
// //
// TODO: Add constructor logic here // TODO: Add constructor logic here
...@@ -57,24 +57,9 @@ namespace PcapDotNet.Packets.Test ...@@ -57,24 +57,9 @@ namespace PcapDotNet.Packets.Test
#endregion #endregion
[TestMethod] [TestMethod]
public void EthernetDatagramTest() public void RandomPacketTest()
{ {
MacAddress ethernetSource = new MacAddress("1:2:3:4:5:6"); Random random = new Random();
MacAddress ethernetDestination = new MacAddress("7:8:9:10:11:12");
const EthernetType ethernetType = EthernetType.IpV4;
Datagram ethernetPayload = new Datagram(new byte[] {1, 2, 3, 4, 5});
Packet goodPacket = PacketBuilder.Ethernet(DateTime.Now,
ethernetSource, ethernetDestination,
ethernetType,
ethernetPayload);
Packet badPacket = new Packet(new byte[]{1,2,3,4,5}, DateTime.Now, new DataLink(DataLinkKind.Ethernet));
Assert.IsTrue(goodPacket.Ethernet.IsValid);
Assert.AreEqual(ethernetSource, goodPacket.Ethernet.Source);
Assert.AreEqual(ethernetDestination, goodPacket.Ethernet.Destination);
Assert.AreEqual(ethernetType, goodPacket.Ethernet.EtherType);
Assert.IsFalse(badPacket.Ethernet.IsValid);
} }
} }
} }
\ No newline at end of file
...@@ -42,8 +42,10 @@ ...@@ -42,8 +42,10 @@
</Reference> </Reference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="EthernetDatagramTests.cs" /> <Compile Include="EndianitiyTests.cs" />
<Compile Include="EthernetTests.cs" />
<Compile Include="IpV4Tests.cs" /> <Compile Include="IpV4Tests.cs" />
<Compile Include="PacketTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="IpV4AddressTests.cs" /> <Compile Include="IpV4AddressTests.cs" />
</ItemGroup> </ItemGroup>
......
...@@ -9,6 +9,48 @@ namespace PcapDotNet.Packets.TestUtils ...@@ -9,6 +9,48 @@ namespace PcapDotNet.Packets.TestUtils
{ {
public static class MoreRandomPackets public static class MoreRandomPackets
{ {
public static Datagram NextDatagram(this Random random, int length)
{
byte[] buffer = new byte[length];
random.NextBytes(buffer);
return new Datagram(buffer);
}
public static MacAddress NextMacAddress(this Random random)
{
return new MacAddress(random.NextUInt48());
}
public static EthernetType NextEthernetType(this Random random)
{
return random.NextEnum(EthernetType.None);
}
public static Packet NextEthernet(this Random random, int packetSize, DateTime timestamp, MacAddress ethernetSource, MacAddress ethernetDestination)
{
if (packetSize < EthernetDatagram.HeaderLength)
throw new ArgumentOutOfRangeException("packetSize", packetSize, "Must be at least the ethernet header length (" + EthernetDatagram.HeaderLength + ")");
return PacketBuilder.Ethernet(timestamp,
ethernetSource, ethernetDestination, random.NextEthernetType(),
random.NextDatagram(packetSize - EthernetDatagram.HeaderLength));
}
public static Packet NextEthernet(this Random random, int packetSize, DateTime timestamp, string ethernetSource, string ethernetDestination)
{
return random.NextEthernet(packetSize, timestamp, new MacAddress(ethernetSource), new MacAddress(ethernetDestination));
}
public static Packet NextEthernet(this Random random, int packetSize, string ethernetSource, string ethernetDestination)
{
return random.NextEthernet(packetSize, DateTime.Now, ethernetSource, ethernetDestination);
}
public static Packet NextEthernet(this Random random, int packetSize)
{
return random.NextEthernet(packetSize, DateTime.Now, random.NextMacAddress(), random.NextMacAddress());
}
public static IpV4Address NextIpV4Address(this Random random) public static IpV4Address NextIpV4Address(this Random random)
{ {
return new IpV4Address(random.NextUInt()); return new IpV4Address(random.NextUInt());
......
...@@ -105,13 +105,18 @@ namespace PcapDotNet.Packets ...@@ -105,13 +105,18 @@ namespace PcapDotNet.Packets
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "ushort")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "ushort")]
protected ushort ReadUShort(int offset, Endianity endianity) protected ushort ReadUShort(int offset, Endianity endianity)
{ {
return _buffer.ReadUShort(StartOffset + offset, endianity); return Buffer.ReadUShort(StartOffset + offset, endianity);
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "uint")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "uint")]
protected uint ReadUInt(int offset, Endianity endianity) protected uint ReadUInt(int offset, Endianity endianity)
{ {
return _buffer.ReadUInt(StartOffset + offset, endianity); return Buffer.ReadUInt(StartOffset + offset, endianity);
}
protected MacAddress ReadMacAddress(int offset, Endianity endianity)
{
return Buffer.ReadMacAddress(StartOffset + offset, endianity);
} }
private static readonly Datagram _empty = new Datagram(new byte[0], 0, 0); private static readonly Datagram _empty = new Datagram(new byte[0], 0, 0);
......
namespace PcapDotNet.Packets
{
public enum Endianity : byte
{
Small,
Big
}
}
\ No newline at end of file
...@@ -22,6 +22,11 @@ namespace PcapDotNet.Packets ...@@ -22,6 +22,11 @@ namespace PcapDotNet.Packets
public const int HeaderLength = 14; public const int HeaderLength = 14;
public Datagram Payload
{
get { return IpV4; }
}
public int PayloadLength public int PayloadLength
{ {
get { return Math.Max(0, Length - HeaderLength); } get { return Math.Max(0, Length - HeaderLength); }
...@@ -31,7 +36,7 @@ namespace PcapDotNet.Packets ...@@ -31,7 +36,7 @@ namespace PcapDotNet.Packets
{ {
get get
{ {
return new MacAddress(Buffer, StartOffset + Offset.Source); return ReadMacAddress(Offset.Source, Endianity.Big);
} }
} }
...@@ -39,7 +44,7 @@ namespace PcapDotNet.Packets ...@@ -39,7 +44,7 @@ namespace PcapDotNet.Packets
{ {
get get
{ {
return new MacAddress(Buffer, StartOffset + Offset.Destination); return ReadMacAddress(Offset.Destination, Endianity.Big);
} }
} }
...@@ -89,9 +94,8 @@ namespace PcapDotNet.Packets ...@@ -89,9 +94,8 @@ namespace PcapDotNet.Packets
internal static void WriteHeader(byte[] buffer, int offset, MacAddress ethernetSource, MacAddress ethernetDestination, EthernetType ethernetType) internal static void WriteHeader(byte[] buffer, int offset, MacAddress ethernetSource, MacAddress ethernetDestination, EthernetType ethernetType)
{ {
ethernetSource.Write(buffer, offset + Offset.Source); buffer.Write(offset + Offset.Source, ethernetSource, Endianity.Big);
ethernetDestination.Write(buffer, offset + Offset.Destination); buffer.Write(offset + Offset.Destination, ethernetDestination, Endianity.Big);
ethernetDestination.Write(buffer, offset + Offset.Destination);
buffer.Write(offset + Offset.EtherTypeLength, (ushort)ethernetType, Endianity.Big); buffer.Write(offset + Offset.EtherTypeLength, (ushort)ethernetType, Endianity.Big);
} }
......
using System; using System;
using System.Globalization; using System.Globalization;
using PcapDotNet.Base;
namespace PcapDotNet.Packets namespace PcapDotNet.Packets
{ {
public struct MacAddress public struct MacAddress
{ {
public MacAddress(byte[] buffer, int offset) public MacAddress(UInt48 value)
{ {
_b1 = buffer[offset++]; _value = value;
_b2 = buffer[offset++];
_b3 = buffer[offset++];
_b4 = buffer[offset++];
_b5 = buffer[offset++];
_b6 = buffer[offset];
} }
public MacAddress(string address) public MacAddress(string address)
...@@ -20,22 +16,23 @@ namespace PcapDotNet.Packets ...@@ -20,22 +16,23 @@ namespace PcapDotNet.Packets
string[] hexes = address.Split(':'); string[] hexes = address.Split(':');
if (hexes.Length != 6) if (hexes.Length != 6)
throw new ArgumentException("Failed parsing " + address + " as mac address. Expected 6 hexes and got " + hexes.Length + " hexes", "address"); throw new ArgumentException("Failed parsing " + address + " as mac address. Expected 6 hexes and got " + hexes.Length + " hexes", "address");
_b1 = Convert.ToByte(hexes[0], 16);
_b2 = Convert.ToByte(hexes[1], 16); _value = (UInt48)(((long)Convert.ToByte(hexes[0], 16) << 40) |
_b3 = Convert.ToByte(hexes[2], 16); ((long)Convert.ToByte(hexes[1], 16) << 32) |
_b4 = Convert.ToByte(hexes[3], 16); ((long)Convert.ToByte(hexes[2], 16) << 24) |
_b5 = Convert.ToByte(hexes[4], 16); ((long)Convert.ToByte(hexes[3], 16) << 16) |
_b6 = Convert.ToByte(hexes[5], 16); ((long)Convert.ToByte(hexes[4], 16) << 8) |
Convert.ToByte(hexes[5], 16));
}
public UInt48 ToValue()
{
return _value;
} }
public bool Equals(MacAddress other) public bool Equals(MacAddress other)
{ {
return _b1 == other._b1 && return _value == other._value;
_b2 == other._b2 &&
_b3 == other._b3 &&
_b4 == other._b4 &&
_b5 == other._b5 &&
_b6 == other._b6;
} }
public override bool Equals(object obj) public override bool Equals(object obj)
...@@ -56,15 +53,30 @@ namespace PcapDotNet.Packets ...@@ -56,15 +53,30 @@ namespace PcapDotNet.Packets
public override int GetHashCode() public override int GetHashCode()
{ {
return (_b1 + (_b2 << 8) + (_b3 << 16) + (_b4 << 24)).GetHashCode() ^ return _value.GetHashCode();
(_b5 + (_b6 << 8)).GetHashCode();
} }
public override string ToString() public override string ToString()
{ {
return string.Format(CultureInfo.InvariantCulture, "{0:X2}:{1:X2}:{2:X2}:{3:X2}:{4:X2}:{5:X2}", _b1, _b2, _b3, _b4, _b5, _b6); return string.Format(CultureInfo.InvariantCulture, "{0:X2}:{1:X2}:{2:X2}:{3:X2}:{4:X2}:{5:X2}",
(byte)(_value >> 40),
(byte)(_value >> 32),
(byte)(_value >> 24),
(byte)(_value >> 16),
(byte)(_value >> 8),
(byte)(_value));
} }
/* internal MacAddress(byte[] buffer, int offset)
{
_b1 = buffer[offset++];
_b2 = buffer[offset++];
_b3 = buffer[offset++];
_b4 = buffer[offset++];
_b5 = buffer[offset++];
_b6 = buffer[offset];
}
internal void Write(byte[] buffer, int offset) internal void Write(byte[] buffer, int offset)
{ {
buffer[offset++] = _b1; buffer[offset++] = _b1;
...@@ -74,12 +86,13 @@ namespace PcapDotNet.Packets ...@@ -74,12 +86,13 @@ namespace PcapDotNet.Packets
buffer[offset++] = _b5; buffer[offset++] = _b5;
buffer[offset] = _b6; buffer[offset] = _b6;
} }
*/
private readonly byte _b1; private readonly UInt48 _value;
private readonly byte _b2; // private readonly byte _b1;
private readonly byte _b3; // private readonly byte _b2;
private readonly byte _b4; // private readonly byte _b3;
private readonly byte _b5; // private readonly byte _b4;
private readonly byte _b6; // private readonly byte _b5;
// private readonly byte _b6;
} }
} }
\ No newline at end of file
...@@ -145,8 +145,8 @@ namespace PcapDotNet.Packets ...@@ -145,8 +145,8 @@ namespace PcapDotNet.Packets
buffer[offset + Offset.Ttl] = ttl; buffer[offset + Offset.Ttl] = ttl;
buffer[offset + Offset.Protocol] = (byte)protocol; buffer[offset + Offset.Protocol] = (byte)protocol;
buffer.Write(offset + Offset.Source, source.ToValue(), Endianity.Big); buffer.Write(offset + Offset.Source, source, Endianity.Big);
buffer.Write(offset + Offset.Destination, destination.ToValue(), Endianity.Big); buffer.Write(offset + Offset.Destination, destination, Endianity.Big);
options.Write(buffer, offset + Offset.Options); options.Write(buffer, offset + Offset.Options);
buffer.Write(offset + Offset.HeaderChecksum, Sum16BitsToChecksum(Sum16Bits(buffer, offset, headerLength)), Endianity.Big); buffer.Write(offset + Offset.HeaderChecksum, Sum16BitsToChecksum(Sum16Bits(buffer, offset, headerLength)), Endianity.Big);
......
...@@ -52,7 +52,7 @@ namespace PcapDotNet.Packets ...@@ -52,7 +52,7 @@ namespace PcapDotNet.Packets
buffer[offset++] = (byte)Length; buffer[offset++] = (byte)Length;
buffer[offset++] = (byte)(OptionMinimumLength + 1 + PointedAddressIndex * 4); buffer[offset++] = (byte)(OptionMinimumLength + 1 + PointedAddressIndex * 4);
for (int i = 0; i != _addresses.Length; ++i) for (int i = 0; i != _addresses.Length; ++i)
buffer.Write(ref offset, _addresses[i].ToValue(), Endianity.Big); buffer.Write(ref offset, _addresses[i], Endianity.Big);
} }
protected static bool TryRead(out IpV4Address[] addresses, out byte pointedAddressIndex, protected static bool TryRead(out IpV4Address[] addresses, out byte pointedAddressIndex,
......
...@@ -49,7 +49,7 @@ namespace PcapDotNet.Packets ...@@ -49,7 +49,7 @@ namespace PcapDotNet.Packets
{ {
foreach (KeyValuePair<IpV4Address, TimeSpan> addressAndTimestamp in _addressesAndTimestamps) foreach (KeyValuePair<IpV4Address, TimeSpan> addressAndTimestamp in _addressesAndTimestamps)
{ {
buffer.Write(ref offset, addressAndTimestamp.Key.ToValue(), Endianity.Big); buffer.Write(ref offset, addressAndTimestamp.Key, Endianity.Big);
buffer.Write(ref offset, (uint)addressAndTimestamp.Value.TotalMilliseconds, Endianity.Big); buffer.Write(ref offset, (uint)addressAndTimestamp.Value.TotalMilliseconds, Endianity.Big);
} }
} }
......
...@@ -4,12 +4,6 @@ using PcapDotNet.Base; ...@@ -4,12 +4,6 @@ using PcapDotNet.Base;
namespace PcapDotNet.Packets namespace PcapDotNet.Packets
{ {
public enum Endianity : byte
{
Small,
Big
}
public static class MoreByteArray public static class MoreByteArray
{ {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "short")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "short")]
...@@ -31,7 +25,7 @@ namespace PcapDotNet.Packets ...@@ -31,7 +25,7 @@ namespace PcapDotNet.Packets
public static ushort ReadUShort(this byte[] buffer, ref int offset, Endianity endianity) public static ushort ReadUShort(this byte[] buffer, ref int offset, Endianity endianity)
{ {
ushort result = ReadUShort(buffer, offset, endianity); ushort result = ReadUShort(buffer, offset, endianity);
offset += 2; offset += sizeof(ushort);
return result; return result;
} }
...@@ -46,10 +40,19 @@ namespace PcapDotNet.Packets ...@@ -46,10 +40,19 @@ namespace PcapDotNet.Packets
public static UInt24 ReadUInt24(this byte[] buffer, ref int offset, Endianity endianity) public static UInt24 ReadUInt24(this byte[] buffer, ref int offset, Endianity endianity)
{ {
UInt24 result = ReadUInt24(buffer, offset, endianity); UInt24 result = ReadUInt24(buffer, offset, endianity);
offset += 3; offset += UInt24.SizeOf;
return result; return result;
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "int")]
public static int ReadInt(this byte[] buffer, int offset, Endianity endianity)
{
int value = ReadInt(buffer, offset);
if (IsWrongEndianity(endianity))
value = IPAddress.HostToNetworkOrder(value);
return value;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "uint")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "uint")]
public static uint ReadUInt(this byte[] buffer, int offset, Endianity endianity) public static uint ReadUInt(this byte[] buffer, int offset, Endianity endianity)
{ {
...@@ -60,19 +63,34 @@ namespace PcapDotNet.Packets ...@@ -60,19 +63,34 @@ namespace PcapDotNet.Packets
public static uint ReadUInt(this byte[] buffer, ref int offset, Endianity endianity) public static uint ReadUInt(this byte[] buffer, ref int offset, Endianity endianity)
{ {
uint result = ReadUInt(buffer, offset, endianity); uint result = ReadUInt(buffer, offset, endianity);
offset += 4; offset += sizeof(int);
return result; return result;
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "int")] public static UInt48 ReadUInt48(this byte[] buffer, int offset, Endianity endianity)
public static int ReadInt(this byte[] buffer, int offset, Endianity endianity)
{ {
int value = ReadInt(buffer, offset); UInt48 value = ReadUInt48(buffer, offset);
if (IsWrongEndianity(endianity)) if (IsWrongEndianity(endianity))
value = IPAddress.HostToNetworkOrder(value); value = HostToNetworkOrder(value);
return value; return value;
} }
public static UInt48 ReadUInt48(this byte[] buffer, ref int offset, Endianity endianity)
{
UInt48 result = buffer.ReadUInt48(offset, endianity);
offset += UInt48.SizeOf;
return result;
}
public static MacAddress ReadMacAddress(this byte[] buffer, int offset, Endianity endianity)
{
return new MacAddress(buffer.ReadUInt48(offset, endianity));
}
public static MacAddress ReadMacAddress(this byte[] buffer, ref int offset, Endianity endianity)
{
return new MacAddress(buffer.ReadUInt48(ref offset, endianity));
}
public static IpV4Address ReadIpV4Address(this byte[] buffer, int offset, Endianity endianity) public static IpV4Address ReadIpV4Address(this byte[] buffer, int offset, Endianity endianity)
{ {
...@@ -99,7 +117,7 @@ namespace PcapDotNet.Packets ...@@ -99,7 +117,7 @@ namespace PcapDotNet.Packets
public static void Write(this byte[] buffer, ref int offset, ushort value, Endianity endianity) public static void Write(this byte[] buffer, ref int offset, ushort value, Endianity endianity)
{ {
Write(buffer, offset, value, endianity); Write(buffer, offset, value, endianity);
offset += 2; offset += sizeof(ushort);
} }
public static void Write(this byte[] buffer, int offset, UInt24 value, Endianity endianity) public static void Write(this byte[] buffer, int offset, UInt24 value, Endianity endianity)
...@@ -112,7 +130,7 @@ namespace PcapDotNet.Packets ...@@ -112,7 +130,7 @@ namespace PcapDotNet.Packets
public static void Write(this byte[] buffer, ref int offset, UInt24 value, Endianity endianity) public static void Write(this byte[] buffer, ref int offset, UInt24 value, Endianity endianity)
{ {
Write(buffer, offset, value, endianity); Write(buffer, offset, value, endianity);
offset += 3; offset += UInt24.SizeOf;
} }
public static void Write(this byte[] buffer, int offset, int value, Endianity endianity) public static void Write(this byte[] buffer, int offset, int value, Endianity endianity)
...@@ -130,7 +148,40 @@ namespace PcapDotNet.Packets ...@@ -130,7 +148,40 @@ namespace PcapDotNet.Packets
public static void Write(this byte[] buffer, ref int offset, uint value, Endianity endianity) public static void Write(this byte[] buffer, ref int offset, uint value, Endianity endianity)
{ {
Write(buffer, offset, value, endianity); Write(buffer, offset, value, endianity);
offset += 4; offset += sizeof(uint);
}
public static void Write(this byte[] buffer, int offset, UInt48 value, Endianity endianity)
{
if (IsWrongEndianity(endianity))
value = HostToNetworkOrder(value);
Write(buffer, offset, value);
}
public static void Write(this byte[] buffer, ref int offset, UInt48 value, Endianity endianity)
{
Write(buffer, offset, value, endianity);
offset += UInt48.SizeOf;
}
public static void Write(this byte[] buffer, int offset, MacAddress value, Endianity endianity)
{
buffer.Write(offset, value.ToValue(), endianity);
}
public static void Write(this byte[] buffer, ref int offset, MacAddress value, Endianity endianity)
{
buffer.Write(ref offset, value.ToValue(), endianity);
}
public static void Write(this byte[] buffer, int offset, IpV4Address value, Endianity endianity)
{
buffer.Write(offset, value.ToValue(), endianity);
}
public static void Write(this byte[] buffer, ref int offset, IpV4Address value, Endianity endianity)
{
buffer.Write(ref offset, value.ToValue(), endianity);
} }
private static bool IsWrongEndianity(Endianity endianity) private static bool IsWrongEndianity(Endianity endianity)
...@@ -146,9 +197,10 @@ namespace PcapDotNet.Packets ...@@ -146,9 +197,10 @@ namespace PcapDotNet.Packets
{ {
UInt24* resultPtr = &result; UInt24* resultPtr = &result;
byte* resultBytePtr = (byte*)resultPtr; byte* resultBytePtr = (byte*)resultPtr;
UInt24* valuePtr = &value;
UInt24* valuePtr = &value;
byte* valueBytePtr = (byte*)valuePtr; byte* valueBytePtr = (byte*)valuePtr;
resultBytePtr[0] = valueBytePtr[2]; resultBytePtr[0] = valueBytePtr[2];
resultBytePtr[1] = valueBytePtr[1]; resultBytePtr[1] = valueBytePtr[1];
resultBytePtr[2] = valueBytePtr[0]; resultBytePtr[2] = valueBytePtr[0];
...@@ -157,6 +209,29 @@ namespace PcapDotNet.Packets ...@@ -157,6 +209,29 @@ namespace PcapDotNet.Packets
return result; return result;
} }
private static UInt48 HostToNetworkOrder(UInt48 value)
{
UInt48 result;
unsafe
{
UInt48* resultPtr = &result;
byte* resultBytePtr = (byte*)resultPtr;
UInt48* valuePtr = &value;
byte* valueBytePtr = (byte*)valuePtr;
resultBytePtr[0] = valueBytePtr[5];
resultBytePtr[1] = valueBytePtr[4];
resultBytePtr[2] = valueBytePtr[3];
resultBytePtr[3] = valueBytePtr[2];
resultBytePtr[4] = valueBytePtr[1];
resultBytePtr[5] = valueBytePtr[0];
}
return result;
}
private static short ReadShort(byte[] buffer, int offset) private static short ReadShort(byte[] buffer, int offset)
{ {
unsafe unsafe
...@@ -190,6 +265,17 @@ namespace PcapDotNet.Packets ...@@ -190,6 +265,17 @@ namespace PcapDotNet.Packets
} }
} }
private static UInt48 ReadUInt48(byte[] buffer, int offset)
{
unsafe
{
fixed (byte* ptr = &buffer[offset])
{
return *((UInt48*)ptr);
}
}
}
private static void Write(byte[] buffer, int offset, short value) private static void Write(byte[] buffer, int offset, short value)
{ {
unsafe unsafe
...@@ -222,5 +308,16 @@ namespace PcapDotNet.Packets ...@@ -222,5 +308,16 @@ namespace PcapDotNet.Packets
} }
} }
} }
private static void Write(byte[] buffer, int offset, UInt48 value)
{
unsafe
{
fixed (byte* ptr = &buffer[offset])
{
*((UInt48*)ptr) = value;
}
}
}
} }
} }
\ No newline at end of file
...@@ -63,6 +63,7 @@ ...@@ -63,6 +63,7 @@
<Compile Include="Datagram.cs" /> <Compile Include="Datagram.cs" />
<Compile Include="DataLink.cs" /> <Compile Include="DataLink.cs" />
<Compile Include="DataLinkKind.cs" /> <Compile Include="DataLinkKind.cs" />
<Compile Include="Endianity.cs" />
<Compile Include="Ethernet\EthernetDatagram.cs" /> <Compile Include="Ethernet\EthernetDatagram.cs" />
<Compile Include="Ethernet\EthernetType.cs" /> <Compile Include="Ethernet\EthernetType.cs" />
<Compile Include="Ethernet\MacAddress.cs" /> <Compile Include="Ethernet\MacAddress.cs" />
......
...@@ -38,11 +38,21 @@ namespace PcapDotNet.TestUtils ...@@ -38,11 +38,21 @@ namespace PcapDotNet.TestUtils
return (uint)random.Next(); return (uint)random.Next();
} }
public static UInt48 NextUInt48(this Random random)
{
return (UInt48)random.NextLong(UInt48.MaxValue + 1);
}
public static long NextLong(this Random random, long minValue, long maxValue) public static long NextLong(this Random random, long minValue, long maxValue)
{ {
return minValue + (long)random.NextULong((ulong)(maxValue - minValue)); return minValue + (long)random.NextULong((ulong)(maxValue - minValue));
} }
public static long NextLong(this Random random, long maxValue)
{
return random.NextLong(0, maxValue);
}
public static long NextLong(this Random random) public static long NextLong(this Random random)
{ {
return (long)random.NextULong(); return (long)random.NextULong();
...@@ -63,22 +73,22 @@ namespace PcapDotNet.TestUtils ...@@ -63,22 +73,22 @@ namespace PcapDotNet.TestUtils
return new DateTime(random.NextLong(DateTime.MinValue.Ticks, DateTime.MaxValue.Ticks + 1)); return new DateTime(random.NextLong(DateTime.MinValue.Ticks, DateTime.MaxValue.Ticks + 1));
} }
public static T NextEnum<T>(this Random random) public static T NextEnum<T>(this Random random, params T[] valuesToIgnore)
{ {
Type type = typeof(T); Type type = typeof(T);
if (!type.IsEnum) if (!type.IsEnum)
throw new ArgumentException("T must be an Enum"); throw new ArgumentException("T must be an Enum");
Array enumValues = Enum.GetValues(type); IList<T> enumValues = new List<T>(((IEnumerable<T>)Enum.GetValues(type)).Except(valuesToIgnore));
if (enumValues.Length == 0) if (enumValues.Count == 0)
throw new ArgumentException("T is an enum with no values", "T"); throw new ArgumentException("T is an enum with no values", "T");
return (T)random.NextValue(enumValues); return (T)random.NextValue(enumValues);
} }
public static object NextValue(this Random random, Array values) public static object NextValue<T>(this Random random, IList<T> values)
{ {
return values.GetValue(random.Next(values.Length)); return values[random.Next(values.Count)];
} }
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment