A Bark logging handler logging output to a datagram (UDP) socket.
    The server listening at the given 'host' and 'port' will be sent a
    pickled dictionary.

    Similar to logging.handlers.DatagramHandler.
961424
def datagram_handler(name, logname, host, port):
    

    return wrap_log_handler(logging.handlers.DatagramHandler(host, port))
1338561
def __telnet_event_listener(self, ip, callback):
        """"""

        tn = telnetlib.Telnet(ip, 2708)
        self._last_event = ""
        self._telnet_running = True
        while self._telnet_running:
            try:
                raw_string = tn.read_until(b'.\n', 5)

                if len(raw_string) >= 2 and raw_string[-2:] == b'.\n':
                    # lightpad sends ".\n" at the end that we need to chop off
                    json_string = raw_string.decode('ascii')[0:-2]
                    if json_string != self._last_event:
                        callback(json.loads(json_string))

                    self._last_event = json_string

            except:
                pass
        tn.close()
140816
function onListening() {
    const addr = server.address();
    const bind = (typeof addr === 'string')
                ? 'pipe ' + addr
                : 'port ' + addr.port;
    debugServer('Listening on ' + bind);
  }
1089223
def packet_in_handler(self, req_pkt, req_igmp, msg):
        """"""
        dpid = msg.datapath.id
        ofproto = msg.datapath.ofproto
        if ofproto.OFP_VERSION == ofproto_v1_0.OFP_VERSION:
            in_port = msg.in_port
        else:
            in_port = msg.match['in_port']

        log = "SW=%s PORT=%d IGMP received. " % (
            dpid_to_str(dpid), in_port)
        self.logger.debug(str(req_igmp))
        if igmp.IGMP_TYPE_QUERY == req_igmp.msgtype:
            self.logger.info(log + "[QUERY]")
            (req_ipv4, ) = req_pkt.get_protocols(ipv4.ipv4)
            (req_eth, ) = req_pkt.get_protocols(ethernet.ethernet)
            self._do_query(req_igmp, req_ipv4, req_eth, in_port, msg)
        elif (igmp.IGMP_TYPE_REPORT_V1 == req_igmp.msgtype or
              igmp.IGMP_TYPE_REPORT_V2 == req_igmp.msgtype):
            self.logger.info(log + "[REPORT]")
            self._do_report(req_igmp, in_port, msg)
        elif igmp.IGMP_TYPE_LEAVE == req_igmp.msgtype:
            self.logger.info(log + "[LEAVE]")
            self._do_leave(req_igmp, in_port, msg)
        elif igmp.IGMP_TYPE_REPORT_V3 == req_igmp.msgtype:
            self.logger.info(log + "V3 is not supported yet.")
            self._do_flood(in_port, msg)
        else:
            self.logger.info(log + "[unknown type:%d]",
                             req_igmp.msgtype)
            self._do_flood(in_port, msg)
1092726
def handle(self):
        
        # Unpack the data from the request
        data, socket = self.request
        
        try:
            # Parse it as JSON
            message_attrs = json.loads(data.decode('utf-8'))
            # Fluff it up into a proper logging record
            record = logging.makeLogRecord(message_attrs)
        except:
            # Complain someone is sending us bad logging data
            logging.error("Malformed log message from {}".format(self.client_address[0]))
        else:
            # Log level filtering should have been done on the remote end. The handle() method
            # skips it on this end.
            log.handle(record)
318776
def check_udp(helper, host, port, session):
    
    open_ports = walk_data(session, '.1.3.6.1.2.1.7.5.1.2', helper)[0] # the udpLocaLPort from UDP-MIB.mib (deprecated)
    
    # here we show all open UDP ports
    if scan:
        print "All open UDP ports at host " + host
        for port in open_ports:
            print "UDP: \t" + port
        quit()
    
    if port in open_ports:        
        udp_status = "OPEN"
    else:
        udp_status = "CLOSED"
        helper.status(critical)
    return ("Current status for UDP port " + port + " is: " + udp_status)
420607
def do_log(self, target, nick, msg, msgtype):
        
        if not isinstance(msg, str):
            raise Exception("IRC doesn't like it when you send it a %s" % type(msg).__name__)
        target = target.lower()
        flags = 0
        # Properly handle /msg +#channel
        if target.startswith(('+', '@')):
            target = target[1:]
        with self.data_lock:
            if target in self.channels:
                if self.opers[target].get(nick, False):
                    flags |= 1
                if self.voiced[target].get(nick, False):
                    flags |= 2
            else:
                target = 'private'
        # FIXME: should we special-case this?
        # strip ctrl chars from !creffett
        msg = msg.replace('\x02\x038,4', '<rage>')
        self.db.log(nick, target, flags, msg, msgtype)

        if self.log_to_ctrlchan:
            ctrlchan = self.config['core']['ctrlchan']
            if target != ctrlchan:
                ctrlmsg = "%s:%s:%s:%s" % (target, msgtype, nick, msg)
                # If we call self.send, we'll get a infinite loop.
                self.connection.privmsg(ctrlchan, ctrlmsg.strip())
168605
def SocketWriter(host, port, af=None, st=None):
    
    import socket
    if af is None:
        af = socket.AF_INET
    if st is None:
        st = socket.SOCK_STREAM
    message = '({0}): {1}'
    s = socket.socket(af, st)
    s.connect(host, port)
    try:
        while True:
            logstr = (yield)
            s.send(logstr)
    except GeneratorExit:
        s.close()
1220604
public void udpPacketReceived(String sender, String host, int port) {

		// Debug
		if (debugHeartbeats) {
			logger.info("Discovery message received from \"" + sender + "\" node (host: " + host + ", port: " + port
					+ ").");
		}

		// Register as offline node (if unknown)
		registerAsNewNode(sender, host, port);
	}
1072067
function appender(configuration)
{
	var socket = dgram.createSocket('udp4');

	return function(loggingEvent)
	{
		var loggingObject =
		{
			name: loggingEvent.categoryName,
			message: layout(loggingEvent),
			severity: loggingEvent.level.level,
			severityText: loggingEvent.level.levelStr,
		};

		if (configuration.application)
		{
			loggingObject.application = configuration.application;
		}

		if (configuration.environment)
		{
			loggingObject.environment = configuration.environment;
		}

		if (MDC && MDC.active)
		{
			Object.keys(MDC.active).forEach(function(key)
			{
				loggingObject[key] = MDC.active[key];
			});
		}

		send(socket, configuration.host, configuration.port, loggingObject);
	};
}
1017135
function onListening() {
		let addr = server.address()
		let bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port
		debug('Listening on ' + bind)
		console.log('Listening on ' + bind)
	}
720914
async def tcp_echo_client(message, loop, host, port):
    """"""
    print("Connecting to server at %s:%d" % (host, port))
    reader, writer = await asyncio.open_connection(host, port, loop=loop)

    writer.write(message.encode())
    print('Sent: %r' % message)

    data = await reader.read(100)
    print('Received: %r' % data.decode())

    writer.close()
1229184
def _check_port(host, port, socket_type):
        
        if socket_type == "UDP":
            socket_type = socket.SOCK_DGRAM
        else:
            socket_type = socket.SOCK_STREAM

        for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket_type, 0, socket.AI_PASSIVE):
            af, socktype, proto, _, sa = res
            with socket.socket(af, socktype, proto) as s:
                s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                s.bind(sa)  # the port is available if bind is a success
            return True
1017900
def socket_recv(self):
        
        try:
            data = self.sock.recv(2048)
        except socket.error, ex:
            print ("?? socket.recv() error '%d:%s' from %s" %
                (ex[0], ex[1], self.addrport()))
            raise BogConnectionLost()

        ## Did they close the connection?
        size = len(data)
        if size == 0:
            raise BogConnectionLost()

        ## Update some trackers
        self.last_input_time = time.time()
        self.bytes_received += size

        ## Test for telnet commands
        for byte in data:
            self._iac_sniffer(byte)

        ## Look for newline characters to get whole lines from the buffer
        while True:
            mark = self.recv_buffer.find('\n')
            if mark == -1:
                break
            cmd = self.recv_buffer[:mark].strip()
            self.command_list.append(cmd)
            self.cmd_ready = True
            self.recv_buffer = self.recv_buffer[mark+1:]
275812
def get_host_finger(protocol, ip, port, timeout=5):
    
    client = None
    msg = b"Hello, Server\r\n"
    if protocol == 'tcp':
        # tcp 协议
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.settimeout(timeout)
        client.connect((ip, port))
        client.send(msg)
    elif protocol == 'udp':
        # udp 协议
        client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        client.settimeout(timeout)
        client.sendto(msg, (ip, port))
    else:
        raise Exception('协议不支持')

    serverFinger = client.recv(1024)
    client.close()
    return serverFinger
633233
def wireHandlers(cfg):
    
    logger = logging.getLogger('recorder')
    httpPoster = cfg.handlers.get('remote')
    csvLogger = cfg.handlers.get('local')
    activeHandler = None
    if httpPoster is None:
        if csvLogger is None:
            logger.warning("App is running with discard handler only, ALL DATA WILL BE DISCARDED!!!")
        else:
            logger.info("App is running in standalone mode, logging data to local filesystem")
            activeHandler = csvLogger
    else:
        logger.info("App is running against remote server, logging data to " + httpPoster.target)
        activeHandler = httpPoster
        heartbeater.serverURL = httpPoster.target
        heartbeater.ping()

    if activeHandler is not None:
        for device in cfg.recordingDevices.values():
            if activeHandler is httpPoster:
                httpPoster.deviceName = device.name
            copied = copy.copy(activeHandler)
            device.dataHandler = copied if not cfg.useAsyncHandlers else AsyncHandler('recorder', copied)
82546
def listen(self, timeout=10):
        
        self._socket.settimeout(float(timeout))
        while not self.stopped.isSet():
            try:
                data, client_address = self._socket.recvfrom(4096)
            except socket.timeout:
                continue
            try:

                self.receive_datagram((data, client_address))
            except RuntimeError:
                logger.exception("Exception with Executor")
        self._socket.close()