Packets coming up the stack are APDU's.
977994
def confirmation(self, pdu):
        """"""
        if _debug: StateMachineAccessPoint._debug("confirmation %r", pdu)

        # check device communication control
        if self.dccEnableDisable == 'enable':
            if _debug: StateMachineAccessPoint._debug("    - communications enabled")
        elif self.dccEnableDisable == 'disable':
            if (pdu.apduType == 0) and (pdu.apduService == 17):
                if _debug: StateMachineAccessPoint._debug("    - continue with DCC request")
            elif (pdu.apduType == 0) and (pdu.apduService == 20):
                if _debug: StateMachineAccessPoint._debug("    - continue with reinitialize device")
            elif (pdu.apduType == 1) and (pdu.apduService == 8):
                if _debug: StateMachineAccessPoint._debug("    - continue with Who-Is")
            else:
                if _debug: StateMachineAccessPoint._debug("    - not a Who-Is, dropped")
                return
        elif self.dccEnableDisable == 'disableInitiation':
            if _debug: StateMachineAccessPoint._debug("    - initiation disabled")

        # make a more focused interpretation
        atype = apdu_types.get(pdu.apduType)
        if not atype:
            StateMachineAccessPoint._warning("    - unknown apduType: %r", pdu.apduType)
            return

        # decode it
        apdu = atype()
        apdu.decode(pdu)
        if _debug: StateMachineAccessPoint._debug("    - apdu: %r", apdu)

        if isinstance(apdu, ConfirmedRequestPDU):
            # find duplicates of this request
            for tr in self.serverTransactions:
                if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
                    break
            else:
                # build a server transaction
                tr = ServerSSM(self, apdu.pduSource)

                # add it to our transactions to track it
                self.serverTransactions.append(tr)

            # let it run with the apdu
            tr.indication(apdu)

        elif isinstance(apdu, UnconfirmedRequestPDU):
            # deliver directly to the application
            self.sap_request(apdu)

        elif isinstance(apdu, SimpleAckPDU) \
            or isinstance(apdu, ComplexAckPDU) \
            or isinstance(apdu, ErrorPDU) \
            or isinstance(apdu, RejectPDU):

            # find the client transaction this is acking
            for tr in self.clientTransactions:
                if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
                    break
            else:
                return

            # send the packet on to the transaction
            tr.confirmation(apdu)

        elif isinstance(apdu, AbortPDU):
            # find the transaction being aborted
            if apdu.apduSrv:
                for tr in self.clientTransactions:
                    if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
                        break
                else:
                    return

                # send the packet on to the transaction
                tr.confirmation(apdu)
            else:
                for tr in self.serverTransactions:
                    if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
                        break
                else:
                    return

                # send the packet on to the transaction
                tr.indication(apdu)

        elif isinstance(apdu, SegmentAckPDU):
            # find the transaction being aborted
            if apdu.apduSrv:
                for tr in self.clientTransactions:
                    if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
                        break
                else:
                    return

                # send the packet on to the transaction
                tr.confirmation(apdu)
            else:
                for tr in self.serverTransactions:
                    if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
                        break
                else:
                    return

                # send the packet on to the transaction
                tr.indication(apdu)

        else:
            raise RuntimeError("invalid APDU (8)")
550563
function writePESPackets() {
  var continuityCounters = {};
  var pesWriter = x => {
    if (x.type === 'PESPacket') {
      // var bytePos = 0;
      var counter = continuityCounters[x.pid];
      if (typeof counter === 'undefined') counter = 0;
      counter = counter % 16;
      var packets = [];
      var data = (x.payloads.length === 1) ? x.payloads[0] :
        Buffer.concat(x.payloads);
      var packetLength = data.length;
      if (packetLength > 0xffff) {
        packetLength = 0;
        if (!x.streamID.startsWith('video_stream')) {
          console.log(`Warning: PES packet for pid ${x.pid} is not video and has length greater than 0xffff.`);
        }
      }
      var hpp = Buffer.allocUnsafe(100);
      hpp.writeUIntBE(1, 0, 3);
      hpp.writeUInt8(util.streamNameID[x.streamID], 3);
      hpp.writeUInt16BE(packetLength, 4);
      hpp.writeUInt16BE(
        0x8000 |
        (x.scramblingControl & 0x03) << 12 |
        ((x.priority === true) ? 0x0800 : 0x0000) |
        ((x.dataAlignmentIndicator === true) ? 0x0400 : 0x0000) |
        ((x.copyright === true) ? 0x0200 : 0x0000) |
        ((x.originalOrCopy === true) ? 0x0100 : 0x0000) |
        (x.ptsDtsIndicator & 0x03) << 6 |
        ((x.escrFlag === true) ? 0x0020 : 0x0000) |
        ((x.esRateFlag === true) ? 0x0010 : 0x0000) |
        ((x.dsmTrickModeFlag === true) ? 0x0008 : 0x0000) |
        ((x.additionalCopyInfoFlag === true) ? 0x0004 : 0x0000) |
        ((x.crcFlag === true) ? 0x0002 : 0x0000) |
        ((x.extensionFlag === true) ? 0x0001 : 0x0000), 6);
      var pesHeaderLength =
        (x.ptsDtsIndicator === 2 ? 5 : 0) +
        (x.ptsDtsIndicator === 3 ? 10 : 0);
      hpp.writeUInt8(pesHeaderLength, 8);
      hpp = hpp.slice(0, 9 + pesHeaderLength);
      switch (x.ptsDtsIndicator) {
      case 2:
        writeTimeStamp(x.pts, 0x02, hpp, 9);
        break;
      case 3:
        writeTimeStamp(x.pts, 0x03, hpp, 9);
        writeTimeStamp(x.dts, 0x01, hpp, 14);
        break;
      default:
        break;
      }
      var dataPos = 0;
      var payloadStart = true;
      var available = 184 - hpp.length;
      while (dataPos < (data.length - available)) {
        var nextPacket = {
          type : 'TSPacket',
          packetSync : 0x47,
          transportErrorIndicator : false,
          payloadUnitStartIndicator : payloadStart,
          transportPriority : false,
          pid : x.pid,
          scramblingControl : 0,
          adaptationFieldControl : 1,
          continuityCounter : counter++,
          payload : payloadStart ? Buffer.concat(
            [hpp, data.slice(0, available)]) :
            data.slice(dataPos, dataPos + 184)
        };
        counter = counter % 16;
        dataPos += available;
        packets.push(nextPacket);
        payloadStart = false;
        available = 184;
      }
      if (data.length - dataPos > 0) {
        var adaptationLength = 183 - (payloadStart ?
          (data.length - dataPos) + hpp.length :
          (data.length - dataPos));
        var finalPacket = {
          type : 'TSPacket',
          packetSync : 0x47,
          transportErrorIndicator : false,
          payloadUnitStartIndicator : payloadStart,
          transportPriority : false,
          pid : x.pid,
          scramblingControl : 0,
          adaptationFieldControl : 3,
          continuityCounter : counter++,
          adaptationField : { // padding
            type : 'AdaptationField',
            adaptationFieldLength : adaptationLength,
            discontinuityIndicator : false,
            randomAccessIndicator : false,
            elementaryStreamPriorityIndicator : false,
            pcrFlag : false,
            opcrFlag : false,
            splicingPointFlag : false,
            transportPrivateDataFlag : false,
            adaptationFieldExtensionFlag : false
          },
          payload : payloadStart ?
            Buffer.concat([hpp, data]) : data.slice(dataPos)
        };
        if (finalPacket.adaptationField.adaptationFieldLength === -1) {
          delete finalPacket.adaptationField;
          finalPacket.adaptationFieldControl = 1;
        } else if (finalPacket.adaptationField.adaptationFieldLength === 0) {
          finalPacket.adaptationField = {
            type : 'AdaptationField',
            adaptationFieldLength : 0
          };
        }
        packets.push(finalPacket);
        return H(packets);
      }
      continuityCounters[x.pid] = counter % 16;
    } else { // Is PESPacket
      return H([x]);
    }
  };

  return H.pipeline(H.flatMap(pesWriter));
}
427502
function processMultiBytePacket (o) {
  if (o.multiPacketBuffer) {
    o.multiPacketBuffer = Buffer.concat([Buffer.from(o.multiPacketBuffer), Buffer.from(o.rawDataPacket.slice(k.OBCIGanglionPacket19Bit.dataStart, k.OBCIGanglionPacket19Bit.dataStop))]);
  } else {
    o.multiPacketBuffer = o.rawDataPacket.slice(k.OBCIGanglionPacket19Bit.dataStart, k.OBCIGanglionPacket19Bit.dataStop);
  }
}
1352207
private void verifyChunks( byte[] dataBuf, int dataOff, int len, 
                             byte[] checksumBuf, int checksumOff,
                             int firstChunkOffset, int packetVersion) 
                             throws IOException {
    int chunkOffset = firstChunkOffset;
    while (len > 0) {
      int chunkLen = Math.min(len, bytesPerChecksum - chunkOffset);
      chunkOffset = 0;
      
      checksum.update(dataBuf, dataOff, chunkLen);
      dataOff += chunkLen;

      boolean checksumCorrect;
      if (packetVersion == DataTransferProtocol.PACKET_VERSION_CHECKSUM_FIRST) {
        checksumCorrect = checksum.compare(checksumBuf, checksumOff);
        checksumOff += checksumSize;
      } else {
        // Expect packetVersion == DataTransferProtocol.PACKET_VERSION_CHECKSUM_INLINE
        checksumCorrect = checksum.compare(dataBuf, dataOff);
        dataOff += checksumSize;
      }

      if (!checksumCorrect) {
        if (srcDataNode != null) {
          try {
            LOG.info("report corrupt block " + block + " from datanode " +
                      srcDataNode + " to namenode");
            LocatedBlock lb = new LocatedBlock(block, 
                                            new DatanodeInfo[] {srcDataNode});
            datanode.reportBadBlocks(namespaceId, new LocatedBlock[] {lb});
          } catch (IOException e) {
            LOG.warn("Failed to report bad block " + block + 
                      " from datanode " + srcDataNode + " to namenode");
          }
        }
        throw new IOException("Unexpected checksum mismatch " + 
                              "while writing " + block + " from " + inAddr);
      }

      checksum.reset();
      len -= chunkLen;
    }
  }
1257162
private void maybePushConfigChunk() {
        String currentChunk = responseContent.toString(CHARSET);

        int separatorIndex = currentChunk.indexOf("\n\n\n\n");
        if (separatorIndex > 0) {
            String content = currentChunk.substring(0, separatorIndex);
            streamingConfigObservable.onNext(content.trim());
            responseContent.clear();
            responseContent.writeBytes(currentChunk.substring(separatorIndex + 4).getBytes(CHARSET));
        }
    }
586127
private void setupPayloads() {
        payloads.add(new PayloadType.Audio(3, "gsm"));
        payloads.add(new PayloadType.Audio(4, "g723"));
        payloads.add(new PayloadType.Audio(0, "PCMU", 16000));
    }
1134688
private void readPayloadFromBuffer(final ByteBuffer buffer)
    throws IOException {
    int toRead = payload.length - payloadOffset;
    int available = buffer.remaining();
    toRead = Math.min(toRead, available);
    getLogger().debug("Reading %d payload bytes", toRead);
    buffer.get(payload, payloadOffset, toRead);
    payloadOffset += toRead;


    if (payloadOffset == payload.length) {
      finishedPayload(payload);
    }
  }
170348
@Override
	public boolean handleIncomingData()
	{
		lastRecvActivity = System.currentTimeMillis();
		
		while (inputBuffer.remaining() > 0)
		{		
			if (packetInputBuffer.size() == 0)
			{
				if (inputBuffer.remaining() >= 4) // packet_size = sizeof(int) = 4
				{
					int packetSize = inputBuffer.getInt();
					
					// Security check
					int actualMaxPacketSize = Integer.MAX_VALUE;
					if (maxPacketSize != -1)
						actualMaxPacketSize = trustedConnection ? maxPacketSize : 1024;
					
					if (packetSize > actualMaxPacketSize)
					{
						log.error("#"+id+" packet is too large : "+packetSize+" (maxPacketSize="+actualMaxPacketSize+"), dropping client.");
						return false;
					}
					
					packetInputBuffer.setSize(packetSize);
				}
				else
					return true; // Not enough data to proceed ...
			}
			else
			{
				// Append to current packet
				int readAmount = Math.min(inputBuffer.remaining(), packetInputBuffer.size() - currentInputOffset);
				packetInputBuffer.getFrom(inputBuffer, currentInputOffset, readAmount);
				currentInputOffset += readAmount;
				
				// Packet is complete ?
				if (currentInputOffset == packetInputBuffer.size())
				{
					AbstractPacket packet = unserializePacket(packetInputBuffer);
					if (packet == null)
						return false; // Invalid packet
					packetInputBuffer.clear();
					currentInputOffset = 0;
					
					if (traceEnabled)
	                    log.trace("#"+id+" Received "+packet);
					
					if (listener != null)
						trustedConnection = listener.packetReceived(packet);
				}
			}
		}
		
		return true;
	}
1350297
function pushIps(addresses, announced, useInternalAddresses) {
	if (!useInternalAddresses) {
		addresses = addresses.filter((address) => address.internal === false);
	}

	addresses = addresses
		.filter((address) => address.family === 'IPv4')
		.map((address) => address.address);

	return announced.concat(addresses);
}
1085511
function AtemPacket(msg){
		Packet.call(this);

		this.header.flags = msg[0]>>>3;
		this.header.uid = msg.readUInt16BE(2);
		this.header.fs  = msg.readUInt16BE(4);
		this.header.ls  = msg.readUInt16BE(10);

		if ((this.header.flags & flags.unknown) == flags.unknown) console.log('Unknown Packet flag!');

		if (state === ConnectionState.attempting) {
			if (this.isSync()){
				atem.state = ConnectionState.establishing;
				uid = this.header.uid;
			}
		} else
		if (state === ConnectionState.establishing){
			if (msg.length==12 && !this.isConnect()){
				atem.state = ConnectionState.open;
				clearInterval(syncInterval);
				syncInterval = setInterval(sync, 600);
			}
		}

		if (this.isConnect()) {
			//Do something
		}
		else if ((msg.length == (msg.readUInt16BE(0)&0x7FF) && this.header.uid == uid)){
			const body = msg.slice(12);

			var name, data, cmd, cmdLength, cursor=0;
			while (cursor < body.length-1) {
				cmdLength = body.readUInt16BE(cursor);
				name = body.toString('utf8', cursor+4, cursor+8);
				data = body.slice(cursor+8, cursor+cmdLength);
				cmd = new Command(name, data);
				this.body.commands.push(cmd);
				cursor += cmdLength;

				/**
				 * @event Device#rawCommand
				 * @type {Command}
				 */

				// todo: check foreign sequence number, to prevent the event emitter
				// from emitting the same message twice.
				atem.emit('rawCommand', cmd);
				atem.emit(cmd.name, cmd.data);
			}
		}
		else if (msg.length != (msg.readUInt16BE(0)&0x7FF)) {
			const err = new Error('Message length mismatch');
			self.emit('error', err);
		} else {
			const err2 = new Error('UID mismatch');
			self.emit('error', err2);
		}
	}
128543
async def _go_through_packets_from_fd(self, fd, packet_callback, packet_count=None):
        """"""
        packets_captured = 0
        self._log.debug('Starting to go through packets')

        psml_struct, data = await self._get_psml_struct(fd)

        while True:
            try:
                packet, data = await self._get_packet_from_stream(fd, data, got_first_packet=packets_captured > 0,
                                                                  psml_structure=psml_struct)
            except EOFError:
                self._log.debug('EOF reached')
                break

            if packet:
                packets_captured += 1
                try:
                    packet_callback(packet)
                except StopCapture:
                    self._log.debug('User-initiated capture stop in callback')
                    break

            if packet_count and packets_captured >= packet_count:
                break
464907
function(packet) {
        packet.status = packet.readInt(8);
        packet.oskType = packet.readInt(12);
        // TODO: for some reason, the way we decode it
        //  gives an extra 16 bytes of garbage here. We
        //  should really figure out why that's happening
        //  ... and fix it
        if (packet.buf.length > 36) {
            packet.max = packet.readInt(32);
            packet.initial = packet.readString(36);
        }
        this.emit('start_osk_result', packet);
    }
257906
private void send(ByteBuffer data) {
    try {
      this.socket.send(new DatagramPacket(
              data.array(),
              data.capacity(),
              this.address));
    } catch (IOException ioe) {
      logger.info("Error sending datagram packet to tracker at {}: {}.", this.address, ioe.getMessage());
    }
  }
1330843
def arp_parse(data):
        
        # Iteratize pkt
        pkt = packet.Packet(data)
        i = iter(pkt)
        eth_pkt = next(i)
        # Ensure it's an ethernet frame.
        assert isinstance(eth_pkt, ethernet.ethernet)

        arp_pkt = next(i)
        if not isinstance(arp_pkt, arp.arp):
            raise ARPPacket.ARPUnknownFormat()

        if arp_pkt.opcode not in (ARP_REQUEST, ARP_REPLY):
            raise ARPPacket.ARPUnknownFormat(
                msg='unsupported opcode %d' % arp_pkt.opcode)

        if arp_pkt.proto != ETH_TYPE_IP:
            raise ARPPacket.ARPUnknownFormat(
                msg='unsupported arp ethtype 0x%04x' % arp_pkt.proto)

        return arp_pkt
191130
def mavlink_packet(self, m):
        ''''''
        if m.get_type() == 'SERIAL_CONTROL':
            data = m.data[:m.count]
            s = ''.join(str(chr(x)) for x in data)
            sys.stdout.write(s)
1172728
def _handle_ping(self, packet, protocol):
        
        if 'payload' in packet:
            is_valid_node = True
            node_ids = list(packet['payload'].values())
            for node_id in node_ids:
                if self._repository.get_node(node_id) is None:
                    is_valid_node = False
                    break
            if is_valid_node:
                self._pong(packet, protocol)
        else:
            self._pong(packet, protocol)
480748
boolean add(DatagramPacket packet) {
        if (count == packets.length) {
            // We already filled up to UIO_MAX_IOV messages. This is the max allowed per sendmmsg(...) call, we will
            // try again later.
            return false;
        }
        ByteBuf content = packet.content();
        int len = content.readableBytes();
        if (len == 0) {
            return true;
        }
        NativeDatagramPacket p = packets[count];
        InetSocketAddress recipient = packet.recipient();

        int offset = iovArray.count();
        if (!iovArray.add(content)) {
            // Not enough space to hold the whole content, we will try again later.
            return false;
        }
        p.init(iovArray.memoryAddress(offset), iovArray.count() - offset, recipient);

        count++;
        return true;
    }