generic handler to receive udp datagrams
760577
function receive(msg, rinfo){
    var packet = lob.decloak(msg);
    if(!packet) packet = lob.decode(msg); // accept un-encrypted discovery broadcast hints
    if(!packet) return mesh.log.info('dropping invalid packet from',rinfo,msg.toString('hex'));
    tp.pipe(false, {type:'udp4',ip:rinfo.address,port:rinfo.port}, function(pipe){
      mesh.receive(packet, pipe);
    });
  }
133834
def from_bytes(self, raw):
        ''''''
        if len(raw) < UDP._MINLEN:
            raise NotEnoughDataError("Not enough bytes ({}) to reconstruct an UDP object".format(len(raw)))
        fields = struct.unpack(UDP._PACKFMT, raw[:UDP._MINLEN])
        self._src = fields[0]
        self._dst = fields[1]
        self._len = fields[2]
        self._checksum = fields[3]
        return raw[UDP._MINLEN:]
106650
def nn_recv(socket, *args):
    ""
    if len(args) == 1:
        flags, = args
        pointer = ctypes.c_void_p()
        rtn = _nn_recv(socket, ctypes.byref(pointer), ctypes.c_size_t(-1),
                       flags)
        if rtn < 0:
            return rtn, None
        else:
            return rtn, _create_message(pointer.value, rtn)
    elif len(args) == 2:
        msg_buf, flags = args
        mv_buf = memoryview(msg_buf)
        if mv_buf.readonly:
            raise TypeError('Writable buffer is required')
        rtn = _nn_recv(socket, ctypes.addressof(msg_buf), len(mv_buf), flags)
        return rtn, msg_buf
440281
def handle_raw_packet(self, raw_packet):
        """"""
        log.debug('got packet: %s', raw_packet)
        if rflink_log:
            print(raw_packet, file=rflink_log)
            rflink_log.flush()
        packet = None
        try:
            packet = decode_packet(raw_packet)
        except:
            log.exception('failed to parse packet: %s', packet)

        log.debug('decoded packet: %s', packet)

        if packet:
            if 'ok' in packet:
                # handle response packets internally
                log.debug('command response: %s', packet)
                self._last_ack = packet
                self._command_ack.set()
            else:
                self.handle_packet(packet)
        else:
            log.warning('no valid packet')
65016
def handle(self, pkt, raddress, rport):
        """"""
        if not self.context.tidport:
            self.context.tidport = rport
            log.info("Set remote port for session to %s" % rport)

        # Now check the packet type and dispatch it properly.
        if isinstance(pkt, TftpPacketOACK):
            log.info("Received OACK from server")
            try:
                self.handleOACK(pkt)
            except TftpException as err:
                log.error("Failed to negotiate options: %s" % str(err))
                self.sendError(TftpErrors.FailedNegotiation)
                raise
            else:
                log.debug("Sending ACK to OACK")

                self.sendACK(blocknumber=0)

                log.debug("Changing state to TftpStateExpectDAT")
                return TftpStateExpectDAT(self.context)

        elif isinstance(pkt, TftpPacketDAT):
            # If there are any options set, then the server didn't honour any
            # of them.
            log.info("Received DAT from server")
            if self.context.options:
                log.info("Server ignored options, falling back to defaults")
                self.context.options = { 'blksize': DEF_BLKSIZE }
            return self.handleDat(pkt)

        # Every other packet type is a problem.
        elif isinstance(pkt, TftpPacketACK):
            # Umm, we ACK, the server doesn't.
            self.sendError(TftpErrors.IllegalTftpOp)
            raise TftpException("Received ACK from server while in download")

        elif isinstance(pkt, TftpPacketWRQ):
            self.sendError(TftpErrors.IllegalTftpOp)
            raise TftpException("Received WRQ from server while in download")

        elif isinstance(pkt, TftpPacketERR):
            self.sendError(TftpErrors.IllegalTftpOp)
            log.debug("Received ERR packet: %s", pkt)
            if pkt.errorcode == TftpErrors.FileNotFound:
                raise TftpFileNotFoundError("File not found")
            else:
                raise TftpException("Received ERR from server: {}".format(pkt))

        else:
            self.sendError(TftpErrors.IllegalTftpOp)
            raise TftpException("Received unknown packet type from server: %s" % pkt)

        # By default, no state change.
        return self
1106451
def _dgram_send_and_receive(self, _socket, message, buffer_size=4096, *args):
        """"""
        _socket.send(message.encode('utf-8'))
        data, address = _socket.recvfrom(buffer_size)
        return BytesIO(data)
88094
def data_received(self, data):
        """"""
        self.buffer += data.decode()
        self.log.debug('Received %d bytes from AVR: %s', len(self.buffer), self.buffer)
        self._assemble_buffer()
238752
def _handle_raw_packet(self, raw_packet):
        """"""
        if raw_packet[1:2] == b'\x1f':
            self._reset_timeout()
            year = raw_packet[2]
            month = raw_packet[3]
            day = raw_packet[4]
            hour = raw_packet[5]
            minute = raw_packet[6]
            sec = raw_packet[7]
            week = raw_packet[8]
            self.logger.debug(
                'received date: Year: %s, Month: %s, Day: %s, Hour: %s, '
                'Minute: %s, Sec: %s, Week %s',
                year, month, day, hour, minute, sec, week)
        elif raw_packet[1:2] == b'\x0c':
            states = {}
            changes = []
            for switch in range(0, 16):
                if raw_packet[2+switch:3+switch] == b'\x01':
                    states[format(switch, 'x')] = True
                    if (self.client.states.get(format(switch, 'x'), None)
                            is not True):
                        changes.append(format(switch, 'x'))
                        self.client.states[format(switch, 'x')] = True
                elif raw_packet[2+switch:3+switch] == b'\x02':
                    states[format(switch, 'x')] = False
                    if (self.client.states.get(format(switch, 'x'), None)
                            is not False):
                        changes.append(format(switch, 'x'))
                        self.client.states[format(switch, 'x')] = False
            for switch in changes:
                for status_cb in self.client.status_callbacks.get(switch, []):
                    status_cb(states[switch])
            self.logger.debug(states)
            if self.client.in_transaction:
                self.client.in_transaction = False
                self.client.active_packet = False
                self.client.active_transaction.set_result(states)
                while self.client.status_waiters:
                    waiter = self.client.status_waiters.popleft()
                    waiter.set_result(states)
                if self.client.waiters:
                    self.send_packet()
                else:
                    self._cmd_timeout.cancel()
            elif self._cmd_timeout:
                self._cmd_timeout.cancel()
        else:
            self.logger.warning('received unknown packet: %s',
                                binascii.hexlify(raw_packet))
68238
private DatagramChannel openUdpChannel(InetAddress localAddress, int port, Selector selector) throws IOException {
		DatagramChannel channel = DatagramChannel.open();
		channel.configureBlocking(false);
		// Register selector for reading operations
		channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
		channel.bind(new InetSocketAddress(localAddress, port));
		return channel;
	}
387247
public final UdpServer handle(BiFunction<? super UdpInbound, ? super UdpOutbound, ? extends Publisher<Void>> handler) {
		Objects.requireNonNull(handler, "handler");
		return doOnBound(c -> {
			if (log.isDebugEnabled()) {
				log.debug(format(c.channel(), "Handler is being applied: {}"), handler);
			}

			Mono.fromDirect(handler.apply((UdpInbound) c, (UdpOutbound) c))
			    .subscribe(c.disposeSubscriber());
		});
	}
312383
def _do_POSTGET(self, handler):
        """"""
        # at first, assume that the given path is the actual path and there are
        # no arguments
        self.server._dbg(self.path)

        self.path, self.args = _parse_url(self.path)

        # Extract POST data, if any. Clumsy syntax due to Python 2 and
        # 2to3's lack of a byte literal.
        self.data = u"".encode()
        length = self.headers.get('Content-Length')
        if length and length.isdigit():
            self.data = self.rfile.read(int(length))

        # POST data gets automatically decoded into Unicode. The bytestring
        # will still be available in the bdata attribute.
        self.bdata = self.data
        try:
            self.data = self.data.decode('utf8')
        except UnicodeDecodeError:
            self.data = None

        # Run the handler.
        try:
            handler()
        except:
            self.send_response(500)
            self.end_headers()
            self.wfile.write(format_exc().encode('utf8'))
36999
def _ipc_send(self, sock, message_type, payload):
        '''
        
        '''
        sock.sendall(self._pack(message_type, payload))
        data, msg_type = self._ipc_recv(sock)
        return data
282862
function createDgramServer(options = {}) {
  let isExternalSocket = false;

  if (options.socket instanceof dgram.Socket) {
    isExternalSocket = true;
  }

  const socket = isExternalSocket ? options.socket : dgram.createSocket('udp4');
  const server = new StunServer(socket);

  if (!isExternalSocket) {
    socket.on('error', error => server.emit('error', error));
    server.once('close', () => socket.close());
  }

  return server;
}
17076
def capture_udp_packets():
    
    dev = ev(
        "CAP_DEVICE",
        "lo")

    """
    Ignore ports for forwarding to consolidators:

    Redis VM: 6379, 16379
    RabbitMQ VM: 5672, 15672, 25672

    """

    # http://biot.com/capstats/bpf.html
    default_filter = "udp"
    custom_filter = ev(
        "NETWORK_FILTER",
        default_filter)

    log.info(("starting device={} filter={}")
             .format(
                dev,
                custom_filter))

    kamene.sniff(
        filter=custom_filter,
        prn=handle_packets)

    log.info("done")
1260820
def recv_raw(self, x=MTU):
        """"""  # noqa: E501
        pkt, sa_ll = self.ins.recvfrom(x)
        if self.outs and sa_ll[2] == socket.PACKET_OUTGOING:
            return None, None, None
        ts = get_last_packet_timestamp(self.ins)
        return self.LL, pkt, ts
975009
def pipe_data_received(self, fd, data):
        """"""
        if fd == 2:  # stderr fd number
            self._on_stderr(data)
        elif self._on_data:
            self._on_data(data)
        else:
            self._queued_data.append(data)
569128
def receive(self, msg):
        '''
        
        '''
        handler = getattr(self, 'receive_' + msg.__class__.__name__.lower(), None)
        if handler is None:
            raise InvalidMessageError('Receiving class does not support messages of type: ' + msg.__class__.__name__)
        return handler(msg)