1
0

XorMappedTest.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using Microsoft.VisualStudio.TestTools.UnitTesting;
  2. using STUN.Enums;
  3. using STUN.Messages.StunAttributeValues;
  4. using System;
  5. using System.Linq;
  6. using System.Net;
  7. namespace UnitTest
  8. {
  9. [TestClass]
  10. public class XorMappedTest
  11. {
  12. private static ReadOnlySpan<byte> MagicCookieAndTransactionId => new byte[]
  13. {
  14. 0x21, 0x12, 0xa4, 0x42,
  15. 0xb7, 0xe7, 0xa7, 0x01,
  16. 0xbc, 0x34, 0xd6, 0x86,
  17. 0xfa, 0x87, 0xdf, 0xae
  18. };
  19. private static readonly byte[] XorPort = { 0xa1, 0x47 };
  20. private static readonly byte[] XorIPv4 = { 0xe1, 0x12, 0xa6, 0x43 };
  21. private static readonly byte[] XorIPv6 =
  22. {
  23. 0x01, 0x13, 0xa9, 0xfa,
  24. 0xa5, 0xd3, 0xf1, 0x79,
  25. 0xbc, 0x25, 0xf4, 0xb5,
  26. 0xbe, 0xd2, 0xb9, 0xd9
  27. };
  28. private const ushort Port = 32853;
  29. private readonly IPAddress IPv4 = IPAddress.Parse(@"192.0.2.1");
  30. private readonly IPAddress IPv6 = IPAddress.Parse(@"2001:db8:1234:5678:11:2233:4455:6677");
  31. private readonly byte[] _ipv4Response = new byte[] { 0x00, (byte)IpFamily.IPv4 }.Concat(XorPort).Concat(XorIPv4).ToArray();
  32. private readonly byte[] _ipv6Response = new byte[] { 0x00, (byte)IpFamily.IPv6 }.Concat(XorPort).Concat(XorIPv6).ToArray();
  33. /// <summary>
  34. /// https://tools.ietf.org/html/rfc5769.html
  35. /// </summary>
  36. [TestMethod]
  37. public void TestXorMapped()
  38. {
  39. var t = new XorMappedAddressStunAttributeValue(MagicCookieAndTransactionId)
  40. {
  41. Port = Port,
  42. Family = IpFamily.IPv4,
  43. Address = IPv4
  44. };
  45. Span<byte> temp = stackalloc byte[ushort.MaxValue];
  46. var length4 = t.WriteTo(temp);
  47. Assert.AreNotEqual(0, length4);
  48. Assert.IsTrue(temp[..length4].SequenceEqual(_ipv4Response));
  49. t = new XorMappedAddressStunAttributeValue(MagicCookieAndTransactionId);
  50. Assert.IsTrue(t.TryParse(_ipv4Response));
  51. Assert.AreEqual(t.Port, Port);
  52. Assert.AreEqual(t.Family, IpFamily.IPv4);
  53. Assert.AreEqual(t.Address, IPv4);
  54. t = new XorMappedAddressStunAttributeValue(MagicCookieAndTransactionId);
  55. Assert.IsTrue(t.TryParse(_ipv6Response));
  56. Assert.AreEqual(t.Port, Port);
  57. Assert.AreEqual(t.Family, IpFamily.IPv6);
  58. Assert.AreEqual(t.Address, IPv6);
  59. var length6 = t.WriteTo(temp);
  60. Assert.AreNotEqual(0, length6);
  61. Assert.IsTrue(temp[..length6].SequenceEqual(_ipv6Response));
  62. }
  63. }
  64. }