diff --git a/src/DnsClient/DnsRequestHeader.cs b/src/DnsClient/DnsRequestHeader.cs index 5a8b48aa..699a33b9 100644 --- a/src/DnsClient/DnsRequestHeader.cs +++ b/src/DnsClient/DnsRequestHeader.cs @@ -5,7 +5,9 @@ namespace DnsClient { internal class DnsRequestHeader { +#if !NET6_0_OR_GREATER private static readonly Random s_random = new Random(); +#endif public const int HeaderLength = 12; private ushort _flags = 0; @@ -102,7 +104,14 @@ public void RefreshId() private static ushort GetNextUniqueId() { - return (ushort)s_random.Next(1, ushort.MaxValue); +#if NET6_0_OR_GREATER + return (ushort)Random.Shared.Next(1, ushort.MaxValue); +#else + lock (s_random) + { + return (ushort)s_random.Next(1, ushort.MaxValue); + } +#endif } } } diff --git a/test/DnsClient.Tests/DnsRequestHeaderTest.cs b/test/DnsClient.Tests/DnsRequestHeaderTest.cs index 962c9da9..935646f9 100644 --- a/test/DnsClient.Tests/DnsRequestHeaderTest.cs +++ b/test/DnsClient.Tests/DnsRequestHeaderTest.cs @@ -1,4 +1,5 @@ -using System; +using System.Collections.Concurrent; +using System.Threading.Tasks; using Xunit; namespace DnsClient.Tests @@ -49,5 +50,20 @@ public void DnsRequestHeader_ChangeRecursion() Assert.Equal(DnsOpCode.Notify, header.OpCode); } + + [Fact] + public void DnsRequestHeader_IdIsPseudoUnique() + { + ConcurrentDictionary ids = new ConcurrentDictionary(); + + Parallel.For(0, 1000, i => + { + var header = new DnsRequestHeader(DnsOpCode.Query); + Assert.NotEqual(0, header.Id); + ids.TryAdd(header.Id, 0); + }); + + Assert.True(ids.Count > 950, $"Only {ids.Count} of 1000 ids are unique!"); + } } -} \ No newline at end of file +}