decode static method

StunMessage? decode(
  1. Uint8List data
)

Decode a STUN message from bytes

Implementation

static StunMessage? decode(Uint8List data) {
  if (data.length < 20) return null;

  final buffer = ByteData.view(data.buffer);
  final type = buffer.getUint16(0);
  final length = buffer.getUint16(2);
  final cookie = buffer.getUint32(4);

  // Verify magic cookie
  if (cookie != magicCookie) return null;

  // Extract transaction ID
  final transactionId = data.sublist(8, 20);

  // Parse attributes
  final attributes = <int, Uint8List>{};
  var offset = 20;

  while (offset < 20 + length) {
    final attrType = buffer.getUint16(offset);
    offset += 2;
    final attrLength = buffer.getUint16(offset);
    offset += 2;

    attributes[attrType] = data.sublist(offset, offset + attrLength);
    offset += attrLength;
    // Skip padding
    if (attrLength % 4 != 0) {
      offset += 4 - (attrLength % 4);
    }
  }

  return StunMessage(type, transactionId, attributes);
}