decodeSelf method

  1. @override
void decodeSelf(
  1. RawReader reader
)
override

Decodes state from the bytes.

Implementation

@override
void decodeSelf(RawReader reader) {
  // 4-byte span at index 0
  final v0 = reader.readUint32();
  _v0 = v0;

  // Check IP version
  final version = (v0 >> 28);
  if (version != 4) {
    throw ArgumentError(
        "IPv4 packet version number should be 4, not $version");
  }

  // Get IHL
  final ihl = 0xF & (v0 >> 24);
  if (ihl < 5) {
    throw StateError("IHL has invalid value $ihl (should be between 5 and 7");
  }

  // 4-byte span at index 4
  _v1 = reader.readUint32();

  // 4-byte span at index 8
  _v2 = reader.readUint32();

  // 4-byte source address at index 12
  source = Ip4Address.decode(reader);

  // 4-byte destination address at index 16
  destination = Ip4Address.decode(reader);

  // Calculate options length
  final optionsLength = (4 * ihl) - 20;

  // Options
  options = RawData.decode(reader, optionsLength);

  // Payload
  final payloadLength = 0xFFFF & _v0;
  SelfEncoder payload;
  final protocol = ipProtocolMap[payloadProtocolNumber];
  if (protocol != null) {
    final packetFactory = protocol.packetFactory;
    if (packetFactory != null) {
      final packet = packetFactory();
      if (packet is IpPayload) {
        packet.parentPacket = this;
      }
      packet.decodeSelf(reader.readRawReader(payloadLength));
      payload = packet;
    }
  }
  if (payload == null) {
    payload = RawData.decode(reader, payloadLength);
  }
  super.payload = payload;
}