Exemplo n.º 1
0
    public static StunMessage Parse(byte[] bytes)
    {
      var bits = new Bits(bytes);

      if (bits.Pop() != false || bits.Pop() != false)
      {
        throw new Exception("First two bits must be zeroes.");
      }

      var type = StunMessageType.Parse(bits.PopBits(14));

      var length = BitConverter.ToUInt16(bits.PopLittleEndianBytes(2), 0);

      var magicCookie = BitConverter.ToUInt32(bits.PopLittleEndianBytes(4), 0);
      if (magicCookie != MagicCookie)
      {
        throw new ArgumentException($"The parse magic cookie {magicCookie} doesn't match {MagicCookie}.", nameof(MagicCookie));
      }

      var attributes = new List<StunMessageAttribute>();
      for (var index = 0; index < length; index++)
      {
        attributes.Add(StunMessageAttribute.Parse(bits.PopBits(12 * 8)));
      }

      var id = StunMessageId.Parse(bits.PopLittleEndianBytes(12));

      return new StunMessage(type, attributes, id);
    }
Exemplo n.º 2
0
    public static StunMessageType Parse(Bits bits)
    {
      if (bits.Count != 14)
      {
        throw new ArgumentException("The number of bits must be 14.", nameof(bits));
      }

      var methodBits = new Bits(12);
      var classBits = new Bits(2);

      methodBits.AddBits(bits.PopBits(5));
      classBits.AddBit(bits.Pop());
      methodBits.AddBits(bits.PopBits(3));
      classBits.AddBit(bits.Pop());
      methodBits.AddBits(bits);

      return new StunMessageType(StunMessageMethod.Parse(methodBits), StunMessageClass.Parse(classBits));
    }
Exemplo n.º 3
0
    public StunMessageType(StunMessageMethod method, StunMessageClass @class)
    {
      if (!method.PermittedClasses.Contains(@class))
      {
        throw new ArgumentException($"The class {@class} is not permitted by the method {method}.", nameof(@class));
      }
      
      Name = method.Name + " " + @class.Name;

      var methodBits = new Bits(method.Bits);
      var classBits = new Bits(@class.Bits);
      var bits = new Bits(14);
      bits.AddBits(methodBits.PopBits(5));
      bits.AddBit(classBits.Pop());
      bits.AddBits(methodBits.PopBits(3));
      bits.AddBit(classBits.Pop());
      bits.AddBits(methodBits);

      Bits = bits.ToBitArray();
    }