Python socket.SOCK_DGRAM() Examples

The following are code examples for showing how to use socket.SOCK_DGRAM(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: _pslinux.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self):
        tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM)
        tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM)
        udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM)
        udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM)
        unix = ("unix", socket.AF_UNIX, None)
        self.tmap = {
            "all": (tcp4, tcp6, udp4, udp6, unix),
            "tcp": (tcp4, tcp6),
            "tcp4": (tcp4,),
            "tcp6": (tcp6,),
            "udp": (udp4, udp6),
            "udp4": (udp4,),
            "udp6": (udp6,),
            "unix": (unix,),
            "inet": (tcp4, tcp6, udp4, udp6),
            "inet4": (tcp4, udp4),
            "inet6": (tcp6, udp6),
        } 
Example 2
Project: pyblish-win   Author: pyblish   File: test_timeout.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testRecvfromTimeout(self):
        # Test recvfrom() timeout
        _timeout = 2
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.settimeout(_timeout)
        # Prevent "Address already in use" socket exceptions
        test_support.bind_port(self.sock, self.localhost)

        _t1 = time.time()
        self.assertRaises(socket.error, self.sock.recvfrom, 8192)
        _t2 = time.time()

        _delta = abs(_t1 - _t2)
        self.assertTrue(_delta < _timeout + self.fuzz,
                     "timeout (%g) is %g seconds more than expected (%g)"
                     %(_delta, self.fuzz, _timeout)) 
Example 3
Project: kvmd   Author: pikvm   File: wol.py    GNU General Public License v3.0 6 votes vote down vote up
def __inner_wakeup(self) -> None:
        logger = get_logger(0)
        logger.info("Waking up %s (%s:%s) using Wake-on-LAN ...", self.__mac, self.__ip, self.__port)
        sock: Optional[socket.socket] = None
        try:
            # TODO: IPv6 support: http://lists.cluenet.de/pipermail/ipv6-ops/2014-September/010139.html
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            sock.connect((self.__ip, self.__port))
            sock.send(self.__magic)
        except Exception:
            logger.exception("Can't send Wake-on-LAN packet")
        else:
            logger.info("Wake-on-LAN packet sent")
        finally:
            if sock:
                try:
                    sock.close()
                except Exception:
                    pass 
Example 4
Project: schwebedraht   Author: see-base   File: main_test.py    GNU General Public License v3.0 6 votes vote down vote up
def init_socket():
    global sock

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.connect(("127.0.0.1", 4444))

    ib_send("medien/connected:True")
    ib_send("medien/punkte/punkte:#see-base")

    print("Info-Beamer Verbindung hergestellt")

#def init_audio():
#   global mixer
#
#   mixer.init()
#
#   print("Audiosystem eingerichtet") 
Example 5
Project: ps4-remote-play   Author: kingcreek   File: discovery.py    Apache License 2.0 6 votes vote down vote up
def wake_up(ip, console):
    """Asks a PS4 in standby mode to turn itself on."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(('', 12345))

    credentials = int(console.registration_key, 16)

    data = b'WAKEUP * HTTP/1.1\n'
    data += b'client-type:vr\n'
    data += b'auth-type:R\n'
    data += b'model:w\n'
    data += b'app-type:r\n'
    data += b'user-credential:%d\n' % credentials
    data += b'device-discovery-protocol-version:0020020\n'

    sock.sendto(data, (ip, _DISCOVERY_PORT)) 
Example 6
Project: estim2bapi   Author: fredhatt   File: estimsocket.py    MIT License 6 votes vote down vote up
def open_socket(self):
        if self._udp:
            self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        else:
            self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.serversocket.bind(('', self._port))
        if not self._udp:
            self.serversocket.listen(1) # become a server socket
        
        if self._udp:
            print('UDP Server started ({}:{})... waiting for data.'.format(self._address, self._port))
            return None, None
        else:
            print('TCP Server started ({}:{})... waiting for client to connect.'.format(self._address, self._port))
            conn, addr = self.serversocket.accept()
            print('New client {} connected.'.format(addr[0]))
            print('Running loop.')
            return conn, addr 
Example 7
Project: XFLTReaT   Author: earthquake   File: UDP_generic.py    MIT License 6 votes vote down vote up
def serve(self):
		server_socket = None
		try:
			common.internal_print("Starting module: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
		
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
			whereto = (self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport")))
			server_socket.bind(whereto)
			self.comms_socket = server_socket
			self.serverorclient = 1
			self.authenticated = False

			self.communication_initialization()
			self.communication(False) 
			
		except KeyboardInterrupt:

			self.cleanup()
			return

		self.cleanup()

		return 
Example 8
Project: XFLTReaT   Author: earthquake   File: UDP_generic.py    MIT License 6 votes vote down vote up
def connect(self):
		try:
			common.internal_print("Starting client: {0}".format(self.get_module_name()))
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			self.server_tuple = (self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport")))
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False

			self.do_hello()
			self.communication(False)

		except KeyboardInterrupt:
			self.do_logoff()
			self.cleanup()
			raise
		except socket.error:
			self.cleanup()
			raise

		self.cleanup()

		return 
Example 9
Project: python-lifx-sdk   Author: smarthall   File: network.py    MIT License 6 votes vote down vote up
def __init__(self, address='0.0.0.0', broadcast='255.255.255.255'):
        # Prepare a socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        sock.bind((address, 0))

        self._socket = sock

        self._listener = ListenerThread(sock, self._handle_packet)
        self._listener.start()

        self._packet_handlers = {}

        self._current_handler_id = 0

        self._broadcast = broadcast 
Example 10
Project: coolq-telegram-bot   Author: JogleLew   File: cqsdk.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, server_port, client_port=0, online=True, debug=False):
        self.listeners = []

        self.remote_addr = ("127.0.0.1", server_port)
        self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        self.local_addr = ("127.0.0.1", client_port)
        self.server = APIServer(self.local_addr, APIRequestHandler)

        # Online mode
        #   True: Retrive message from socket API server
        #   False: Send message only
        self.online = online

        # Debug Mode
        #   True: print message instead of sending.
        self.debug = debug 
Example 11
Project: jawfish   Author: war-and-code   File: handlers.py    MIT License 6 votes vote down vote up
def _connect_unixsocket(self, address):
        use_socktype = self.socktype
        if use_socktype is None:
            use_socktype = socket.SOCK_DGRAM
        self.socket = socket.socket(socket.AF_UNIX, use_socktype)
        try:
            self.socket.connect(address)
            # it worked, so set self.socktype to the used type
            self.socktype = use_socktype
        except socket.error:
            self.socket.close()
            if self.socktype is not None:
                # user didn't specify falling back, so fail
                raise
            use_socktype = socket.SOCK_STREAM
            self.socket = socket.socket(socket.AF_UNIX, use_socktype)
            try:
                self.socket.connect(address)
                # it worked, so set self.socktype to the used type
                self.socktype = use_socktype
            except socket.error:
                self.socket.close()
                raise 
Example 12
Project: dogbot   Author: moondropx   File: cqsdk.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, server_port, client_port, online=True, debug=False):
        self.listeners = []

        self.remote_addr = ("127.0.0.1", server_port)
        self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        self.local_addr = ("127.0.0.1", client_port)
        self.server = socketserver.UDPServer(self.local_addr, APIRequestHandler)
        self.server.bot = self
        # Online mode
        #   True: Retrive message from socket API server
        #   False: Send message only
        self.online = online

        # Debug Mode
        #   True: only send private message.
        self.debug = debug

        self.scheduler = BackgroundScheduler(
            timezone='Asia/Tokyo',
            job_defaults={'misfire_grace_time': 60},
        )

        self.scheduler.add_job(self.server_keepalive, 'interval', seconds=30) 
Example 13
Project: unicorn-hat-hd   Author: pimoroni   File: show_my_ip.py    MIT License 5 votes vote down vote up
def get_ip():
    # get IP address
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('8.8.8.8', 80))
    my_ip = s.getsockname()[0]
    print(my_ip)
    s.close()
    return my_ip 
Example 14
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def makeSocket(self):
        """
        The factory method of SocketHandler is here overridden to create
        a UDP socket (SOCK_DGRAM).
        """
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return s 
Example 15
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, address=('localhost', SYSLOG_UDP_PORT),
                 facility=LOG_USER, socktype=None):
        """
        Initialize a handler.

        If address is specified as a string, a UNIX socket is used. To log to a
        local syslogd, "SysLogHandler(address="/dev/log")" can be used.
        If facility is not specified, LOG_USER is used. If socktype is
        specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific
        socket type will be used. For Unix sockets, you can also specify a
        socktype of None, in which case socket.SOCK_DGRAM will be used, falling
        back to socket.SOCK_STREAM.
        """
        logging.Handler.__init__(self)

        self.address = address
        self.facility = facility
        self.socktype = socktype

        if isinstance(address, basestring):
            self.unixsocket = 1
            self._connect_unixsocket(address)
        else:
            self.unixsocket = 0
            if socktype is None:
                socktype = socket.SOCK_DGRAM
            self.socket = socket.socket(socket.AF_INET, socktype)
            if socktype == socket.SOCK_STREAM:
                self.socket.connect(address)
            self.socktype = socktype
        self.formatter = None 
Example 16
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _connect_unixsocket(self, address):
        use_socktype = self.socktype
        if use_socktype is None:
            use_socktype = socket.SOCK_DGRAM
        self.socket = socket.socket(socket.AF_UNIX, use_socktype)
        try:
            self.socket.connect(address)
            # it worked, so set self.socktype to the used type
            self.socktype = use_socktype
        except socket.error:
            self.socket.close()
            if self.socktype is not None:
                # user didn't specify falling back, so fail
                raise
            use_socktype = socket.SOCK_STREAM
            self.socket = socket.socket(socket.AF_UNIX, use_socktype)
            try:
                self.socket.connect(address)
                # it worked, so set self.socktype to the used type
                self.socktype = use_socktype
            except socket.error:
                self.socket.close()
                raise

    # curious: when talking to the unix-domain '/dev/log' socket, a
    #   zero-terminator seems to be required.  this string is placed
    #   into a class variable so that it can be overridden if
    #   necessary. 
Example 17
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def emit(self, record):
        """
        Emit a record.

        The record is formatted, and then sent to the syslog server. If
        exception information is present, it is NOT sent to the server.
        """
        try:
            msg = self.format(record) + '\000'
            """
            We need to convert record level to lowercase, maybe this will
            change in the future.
            """
            prio = '<%d>' % self.encodePriority(self.facility,
                                                self.mapPriority(record.levelname))
            # Message is a string. Convert to bytes as required by RFC 5424
            if type(msg) is unicode:
                msg = msg.encode('utf-8')
            msg = prio + msg
            if self.unixsocket:
                try:
                    self.socket.send(msg)
                except socket.error:
                    self.socket.close() # See issue 17981
                    self._connect_unixsocket(self.address)
                    self.socket.send(msg)
            elif self.socktype == socket.SOCK_DGRAM:
                self.socket.sendto(msg, self.address)
            else:
                self.socket.sendall(msg)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record) 
Example 18
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.port = test_support.bind_port(self.serv) 
Example 19
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def clientSetUp(self):
        self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
Example 20
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testSendtoErrors(self):
        # Testing that sendto doens't masks failures. See #10169.
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.addCleanup(s.close)
        s.bind(('', 0))
        sockname = s.getsockname()
        # 2 args
        with self.assertRaises(UnicodeEncodeError):
            s.sendto(u'\u2620', sockname)
        with self.assertRaises(TypeError) as cm:
            s.sendto(5j, sockname)
        self.assertIn('not complex', str(cm.exception))
        with self.assertRaises(TypeError) as cm:
            s.sendto('foo', None)
        self.assertIn('not NoneType', str(cm.exception))
        # 3 args
        with self.assertRaises(UnicodeEncodeError):
            s.sendto(u'\u2620', 0, sockname)
        with self.assertRaises(TypeError) as cm:
            s.sendto(5j, 0, sockname)
        self.assertIn('not complex', str(cm.exception))
        with self.assertRaises(TypeError) as cm:
            s.sendto('foo', 0, None)
        self.assertIn('not NoneType', str(cm.exception))
        with self.assertRaises(TypeError) as cm:
            s.sendto('foo', 'bar', sockname)
        self.assertIn('an integer is required', str(cm.exception))
        with self.assertRaises(TypeError) as cm:
            s.sendto('foo', None, None)
        self.assertIn('an integer is required', str(cm.exception))
        # wrong number of args
        with self.assertRaises(TypeError) as cm:
            s.sendto('foo')
        self.assertIn('(1 given)', str(cm.exception))
        with self.assertRaises(TypeError) as cm:
            s.sendto('foo', 0, sockname, 4)
        self.assertIn('(4 given)', str(cm.exception)) 
Example 21
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testCrucialConstants(self):
        # Testing for mission critical constants
        socket.AF_INET
        socket.SOCK_STREAM
        socket.SOCK_DGRAM
        socket.SOCK_RAW
        socket.SOCK_RDM
        socket.SOCK_SEQPACKET
        socket.SOL_SOCKET
        socket.SO_REUSEADDR 
Example 22
Project: pyblish-win   Author: pyblish   File: test_socketserver.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def dgram_examine(self, proto, addr):
        s = socket.socket(proto, socket.SOCK_DGRAM)
        s.sendto(TEST_STR, addr)
        buf = data = receive(s, 100)
        while data and '\n' not in buf:
            data = receive(s, 100)
            buf += data
        self.assertEqual(buf, TEST_STR)
        s.close() 
Example 23
Project: xideco   Author: MrYsLab   File: xidekit.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, router_ip_address=None, subscriber_port='43125', publisher_port='43124'):
        """
        The __init__ method sets up all the ZeroMQ "plumbing"

        :param router_ip_address: Xideco Router IP Address - if not specified, it will be set to the local computer
        :param subscriber_port: Xideco router subscriber port. This must match that of the Xideco router
        :param publisher_port: Xideco router publisher port. This must match that of the Xideco router
        :return:
        """

        # If no router address was specified, determine the IP address of the local machine
        if router_ip_address:
            self.router_ip_address = router_ip_address
        else:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            # use the google dns
            s.connect(('8.8.8.8', 0))
            self.router_ip_address = s.getsockname()[0]

        print('\n**************************************')
        print('Using router IP address: ' + self.router_ip_address)
        print('**************************************')

        self.subscriber_port = subscriber_port
        self.publisher_port = publisher_port

        # establish the zeriomq sub and pub sockets
        self.context = zmq.Context()
        self.subscriber = self.context.socket(zmq.SUB)
        connect_string = "tcp://" + self.router_ip_address + ':' + self.subscriber_port
        self.subscriber.connect(connect_string)

        self.publisher = self.context.socket(zmq.PUB)
        connect_string = "tcp://" + self.router_ip_address + ':' + self.publisher_port
        self.publisher.connect(connect_string) 
Example 24
Project: auto-check-in   Author: zeekvfu   File: http_utility.py    GNU General Public License v3.0 5 votes vote down vote up
def test_port_open(logger, ip, port, protocol='tcp', retry=2):
    this_func_name = sys._getframe().f_code.co_name
    retry = retry-1
    socket_type = socket.SOCK_STREAM
    if protocol == 'udp':
        socket_type = socket.SOCK_DGRAM
    elif protocol == 'raw':
        socket_type = socket.SOCK_RAW
    flag = False
    try:
        sock = socket.socket(socket.AF_INET, socket_type)
        sock.settimeout(5)
        sock.connect((ip, port))
        flag = True
    except OverflowError as e:
        logger.error("%s(): OverflowError" % this_func_name)
    except socket.timeout as e:
        logger.error("%s(): socket.timeout" % this_func_name)
        if retry > 0:
            return test_port_open(logger, ip, port, protocol, retry)
    except TimeoutError as e:
        logger.error("%s(): TimeoutError\terrno: %s\tstrerror: %s" % (this_func_name, e.errno, e.strerror))
        if retry > 0:
            return test_port_open(logger, ip, port, protocol, retry)
    except ConnectionRefusedError as e:
        logger.error("%s(): ConnectionRefusedError\terrno: %s\tstrerror: %s" % (this_func_name, e.errno, e.strerror))
        if retry > 0:
            return test_port_open(logger, ip, port, protocol, retry)
    except OSError as e:
        logger.error("%s(): OSError\terrno: %s\tstrerror: %s" % (this_func_name, e.errno, e.strerror))
        if retry > 0:
            return test_port_open(logger, ip, port, protocol, retry)
    finally:
        sock.close()
    logger.info("%s(): retry: %d\tip: %s\tport: %d\tprotocol: %s\tport open: %r" % (this_func_name, retry+1, ip, port, protocol, flag))
    return flag


# 解析得到 URL 对应的 HTML
# 返回值:成功,[delay, content];失败,[-1, exception instance]
# 说明:之所以要返回异常类型,是因为有时侯外层调用者 caller 需要根据异常类型,做针对性地处理 
Example 25
Project: openplotter   Author: openplotter   File: SK-base_d.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, SK_):
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

		self.SK = SK_
		self.nmea_list = []

		data = self.SK.conf.get('NMEA0183', 'sentences')
		try:
			temp_list = eval(data)
		except:
			temp_list = []
		for ii in temp_list:
			self.nmea_list.append(ii)

		self.SK.static_list.append([])
		self.SKb = self.SK.static_list[-1]

		for i in self.nmea_list:
			for ii in i:
				if type(ii) is list:
					for iii in ii:
						if type(iii) is list:
							self.SKb.append([iii[0], [0, 0, 0, 0]])
							iii.append(self.SKb[-1])

		self.cycle_list = []
		index = 0
		for i in self.nmea_list:
			cycle = i[2]
			self.cycle_list.append([cycle, time.time() + cycle, index])
			index += 1 
Example 26
Project: openplotter   Author: openplotter   File: N2K_send.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
		self.empty8 = 0xFF
		self.empty16 = 0xFFFF
		self.empty32 = 0xFFFFFFFF

		self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		self.data = 0 
Example 27
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: wakeonlan.py    MIT License 5 votes vote down vote up
def wakeonlan(module, mac, broadcast, port):
    """ Send a magic Wake-on-LAN packet. """

    mac_orig = mac

    # Remove possible separator from MAC address
    if len(mac) == 12 + 5:
        mac = mac.replace(mac[2], '')

    # If we don't end up with 12 hexadecimal characters, fail
    if len(mac) != 12:
        module.fail_json(msg="Incorrect MAC address length: %s" % mac_orig)

    # Test if it converts to an integer, otherwise fail
    try:
        int(mac, 16)
    except ValueError:
        module.fail_json(msg="Incorrect MAC address format: %s" % mac_orig)

    # Create payload for magic packet
    data = b''
    padding = ''.join(['FFFFFFFFFFFF', mac * 20])
    for i in range(0, len(padding), 2):
        data = b''.join([data, struct.pack('B', int(padding[i: i + 2], 16))])

    # Broadcast payload to network
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

    if not module.check_mode:

        try:
            sock.sendto(data, (broadcast, port))
        except socket.error as e:
            sock.close()
            module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    sock.close() 
Example 28
Project: ps4-remote-play   Author: kingcreek   File: discovery.py    Apache License 2.0 5 votes vote down vote up
def find_console(console, timeout=3.0):
    """Finds a console on the local network and returns its status."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sock.bind(('', 12345))

    data = b'SRCH * HTTP/1.1\r\n'
    data += b'device - discovery - protocol - version:0020020\r\n'
    data += b'\r\n'

    deadline = time.time() + timeout
    while time.time() < deadline:
        sock.sendto(data, ('255.255.255.255', _DISCOVERY_PORT))
        sock.settimeout(deadline - time.time())
        try:
            data, addr = sock.recvfrom(65536)
        except socket.timeout:
            break

        code, headers = _parse_http_response(data)
        if binascii.a2b_hex(headers['host-id']) != console.host_id:
            continue
        if code == 620:
            status = ConsoleStatus.standby
        else:
            status = ConsoleStatus.ready
        return addr[0], status

    return None, None 
Example 29
Project: ps4-remote-play   Author: kingcreek   File: registration.py    Apache License 2.0 5 votes vote down vote up
def _find_console():
    bsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    bsock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    bsock.bind(('', _RP_CONTROL_PORT))

    bsock.sendto(b'SRC2', ('255.255.255.255', _RP_CONTROL_PORT))
    bsock.settimeout(2.0)
    try:
        while True:
            data, (ip, port) = bsock.recvfrom(65536)
            if data[:4] == b'RES2' and port == _RP_CONTROL_PORT:
                return ip
    except socket.timeout:
        return None 
Example 30
Project: spqrel_tools   Author: LCAS   File: io_export_ogreDotScene.py    MIT License 5 votes vote down vote up
def __init__(self):
        import socket
        self.buffer = []    # cmd buffer
        self.socket = sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)   # UDP
        host='localhost'; port = 9420
        sock.connect((host, port))
        print('SERVER: socket connected', sock)
        self._handle = None
        self.setup_callback( bpy.context )
        import threading
        self.ready = threading._allocate_lock()
        self.ID = threading._start_new_thread(
            self.loop, (None,)
        )
        print( 'SERVER: thread started') 
Example 31
Project: flasky   Author: RoseOu   File: statsd.py    MIT License 5 votes vote down vote up
def __init__(self, cfg):
        """host, port: statsD server
        """
        Logger.__init__(self, cfg)
        self.prefix = sub(r"^(.+[^.]+)\.*$", "\g<1>.", cfg.statsd_prefix)
        try:
            host, port = cfg.statsd_host
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.sock.connect((host, int(port)))
        except Exception:
            self.sock = None

    # Log errors and warnings 
Example 32
Project: myhoard   Author: aiven   File: statsd.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, *, host, port=8125, sentry_dsn=None, tags=None):
        self.log = logging.getLogger("StatsClient")
        self.sentry_config = {}
        tags = tags or {}
        sentry_tags = copy(tags)
        sentry_config = {
            "dsn": sentry_dsn or None,
            "hostname": os.environ.get("HOSTNAME") or None,
            "tags": sentry_tags,
            "ignore_exceptions": [],
        }
        self.update_sentry_config(sentry_config)
        self._dest_addr = (host, port)
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.tags = tags 
Example 33
Project: radius-1xtest   Author: shanghai-edu   File: client.py    Apache License 2.0 5 votes vote down vote up
def _SocketOpen(self):
        if not self._socket:
            self._socket=socket.socket(socket.AF_INET,
                                       socket.SOCK_DGRAM)
            self._socket.setsockopt(socket.SOL_SOCKET,
                                    socket.SO_REUSEADDR, 1) 
Example 34
Project: XFLTReaT   Author: earthquake   File: DNS.py    MIT License 5 votes vote down vote up
def serve(self):
		server_socket = None
		if self.zonefile:
			(hostname, self.ttl, self.zone) = self.DNS_common.parse_zone_file(self.zonefile)
			if hostname and (hostname+"." != self.hostname):
				common.internal_print("'hostname' in '{0}' section does not match with the zonefile's origin".format(self.get_module_configname()), -1)
				return
		try:
			common.internal_print("Starting module: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), self.serverport))
		
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
			whereto = (self.config.get("Global", "serverbind"), self.serverport)
			server_socket.bind(whereto)
			self.comms_socket = server_socket
			self.serverorclient = 1
			self.authenticated = False

			self.communication_initialization()
			self.communication(False) 
			
		except KeyboardInterrupt:

			self.cleanup()
			return

		self.cleanup()

		return 
Example 35
Project: XFLTReaT   Author: earthquake   File: DNS.py    MIT License 5 votes vote down vote up
def connect(self):
		try:
			common.internal_print("Using nameserver: {0}".format(self.nameserver))
			common.internal_print("Starting client: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			self.server_tuple = (self.nameserver, self.serverport)
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False
			self.qMTU = self.DNS_proto.reverse_RR_type("A")[4](254, self.hostname, 3, self.upload_encoding_class)

			if self.do_autotune(server_socket):
				self.do_hello()
				self.communication(False)

		except KeyboardInterrupt:
			self.do_logoff()
			self.cleanup()
			raise
		except socket.error:
			self.cleanup()
			raise

		self.cleanup()

		return 
Example 36
Project: XFLTReaT   Author: earthquake   File: DNS.py    MIT License 5 votes vote down vote up
def check(self):
		try:
			common.internal_print("Using nameserver: {0}".format(self.nameserver))
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			self.server_tuple = (self.nameserver, self.serverport)
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False
			self.qMTU = self.DNS_proto.reverse_RR_type("A")[4](255, self.hostname, 4, self.upload_encoding_class)

			self.do_check()
			self.communication(True)

		except KeyboardInterrupt:
			self.cleanup()
			raise
		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
		except socket.error:
			self.cleanup()
			raise

		self.cleanup()

		return 
Example 37
Project: XFLTReaT   Author: earthquake   File: interface.py    MIT License 5 votes vote down vote up
def lin_set_mtu(self, dev, mtu):
		s = socket.socket(type=socket.SOCK_DGRAM)
		try:
			ifr = struct.pack('<16sH', dev, mtu) + '\x00'*14
			fcntl.ioctl(s, self.IOCTL_LINUX_SIOCSIFMTU, ifr)
		except Exception as e:
			common.internal_print("Cannot set MTU ({0}) on interface".format(mtu), -1)
			sys.exit(-1)

		return 
Example 38
Project: XFLTReaT   Author: earthquake   File: interface.py    MIT License 5 votes vote down vote up
def mac_set_mtu(self, dev, mtu):
		s = socket.socket(type=socket.SOCK_DGRAM)
		try:
			ifr = struct.pack('<16sH', self.iface_name, 1350)+'\x00'*14
			fcntl.ioctl(s, self.IOCTL_MACOSX_SIOCSIFMTU, ifr)
		except Exception as e:
			common.internal_print("Cannot set MTU ({0}) on interface".format(mtu), -1)
			sys.exit(-1)

		return 
Example 39
Project: XFLTReaT   Author: earthquake   File: interface.py    MIT License 5 votes vote down vote up
def freebsd_set_mtu(self, dev, mtu):
		s = socket.socket(type=socket.SOCK_DGRAM)
		try:
			ifr = struct.pack('<16sH', self.iface_name, mtu) + '\x00'*14
			fcntl.ioctl(s, self.IOCTL_FREEBSD_SIOCSIFMTU, ifr)
		except Exception as e:
			common.internal_print("Cannot set MTU ({0}) on interface".format(mtu), -1)
			sys.exit(-1)

		return 
Example 40
Project: XFLTReaT   Author: earthquake   File: interface.py    MIT License 5 votes vote down vote up
def freebsd_close_tunnel(self, tun):
		try:
			os.close(tun)
		except:
			pass

		s = socket.socket(type=socket.SOCK_DGRAM)
		try:
			ifr = struct.pack('<16s', self.iface_name) + '\x00'*16
			fcntl.ioctl(s, self.IOCTL_FREEBSD_SIOCIFDESTROY, ifr)
		except Exception as e:
			common.internal_print("Cannot destroy interface: {0}".format(dev), -1)

		return 
Example 41
Project: whatwaff   Author: SVelizDonoso   File: whatwaff.py    MIT License 5 votes vote down vote up
def traceroute(dest_addr, max_hops=30, timeout=0.2):
    print "[*] Verificando Ruta del Servidor :"
    proto_icmp = socket.getprotobyname('icmp')
    proto_udp = socket.getprotobyname('udp')
    port = 33434

    for ttl in xrange(1, max_hops+1):
        rx = socket.socket(socket.AF_INET, socket.SOCK_RAW, proto_icmp)
        rx.settimeout(timeout)
        rx.bind(('', port))
        tx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, proto_udp)
        tx.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
        tx.sendto('', (dest_addr, port))

        try:
            data, curr_addr = rx.recvfrom(512)
            curr_addr = curr_addr[0]
        except socket.error:
            curr_addr = None
        finally:
            rx.close()
            tx.close()

        yield curr_addr

        if curr_addr == dest_addr:
            break 
Example 42
Project: daqnet   Author: adamgreig   File: user.py    MIT License 5 votes vote down vote up
def main():
    args = get_args()
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
    s.connect((args.address, int(args.port)))
    s.send(struct.pack("B", int(args.data, 0)) + b"\x00"*15)
    s.close() 
Example 43
Project: daqnet   Author: adamgreig   File: run_leds.py    MIT License 5 votes vote down vote up
def main():
    args = get_args()
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
    s.connect((args.address, int(args.port)))
    while True:
        for x in range(4):
            set_leds(s, x & 1 == 1, x & 2 == 2)
            time.sleep(0.2) 
Example 44
Project: micropython-barebones   Author: reapzor   File: ntptime.py    MIT License 5 votes vote down vote up
def time():
    NTP_QUERY = bytearray(48)
    NTP_QUERY[0] = 0x1b
    addr = socket.getaddrinfo(host, 123)[0][-1]
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(1)
    res = s.sendto(NTP_QUERY, addr)
    msg = s.recv(48)
    s.close()
    val = struct.unpack("!I", msg[40:44])[0]
    return val - NTP_DELTA

# There's currently no timezone support in MicroPython, so
# utime.localtime() will return UTC time (as if it was .gmtime()) 
Example 45
Project: micropython-barebones   Author: reapzor   File: ntptime.py    MIT License 5 votes vote down vote up
def time():
    NTP_QUERY = bytearray(48)
    NTP_QUERY[0] = 0x1b
    addr = socket.getaddrinfo(host, 123)[0][-1]
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(1)
    res = s.sendto(NTP_QUERY, addr)
    msg = s.recv(48)
    s.close()
    val = struct.unpack("!I", msg[40:44])[0]
    return val - NTP_DELTA

# There's currently no timezone support in MicroPython, so
# utime.localtime() will return UTC time (as if it was .gmtime()) 
Example 46
Project: zabbix   Author: xiaomatech   File: redis_status_analyze.py    MIT License 5 votes vote down vote up
def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(
        fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:
                                                                          24]) 
Example 47
Project: ZbxDsktp   Author: ableev   File: zbxpush.py    MIT License 5 votes vote down vote up
def main():
    args = sys.argv
    zbx_to = args[1]
    zbx_msg = args[2]
    client_port = 10052

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.sendto(bytes(zbx_msg), (zbx_to, client_port)) 
Example 48
Project: ZbxDsktp   Author: ableev   File: zbxlistenerd.py    MIT License 5 votes vote down vote up
def main():

    config = ConfigParser.ConfigParser()
    config.read("settings.cfg")
    conf = dict(config.items('ZbxDsktp'))

    ip = conf["ip"]
    port = int(conf["port"])

    try:
        if conf["growl_enabled"] == "True":
            growl_enabled = True
        else:
            growl_enabled = False
    except:
        growl_enabled = False
    try:
        popupttl = conf["popupttl"]
    except:
        popupttl = "8640000"

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind((ip, port))

    try:
        while True:
            data, addr = sock.recvfrom(10240)
            severity, host, trigger = data.split("@@@")

            icon = "{0}/{1}.png".format(conf["icon_dir"], severity)

            triggers_ignore = [
            "usersversioncheck failed to run ",
            "usersversion is too old ",
            ]
            if trigger not in triggers_ignore:
                send_message(host, trigger, growl_enabled, icon, popupttl)

    except (KeyboardInterrupt, SystemExit):
        print "Exiting..."
        sys.exit() 
Example 49
Project: ipmisim   Author: rhtyd   File: fakesession.py    Apache License 2.0 5 votes vote down vote up
def _xmit_packet(self, retry=True, delay_xmit=None):
        if self.sequencenumber:
            self.sequencenumber += 1
        if delay_xmit is not None:
            # skip transmit, let retry timer do it's thing
            self.waiting_sessions[self] = {}
            self.waiting_sessions[self]['ipmisession'] = self
            self.waiting_sessions[self]['timeout'] = delay_xmit +  _monotonic_time()
            return  
        if self.sockaddr:
            self.send_data(self.netpacket, self.sockaddr)
        else:
            self.allsockaddrs = []
            try:
                for res in socket.getaddrinfo(self.bmc, self.port, 0, socket.SOCK_DGRAM):
                    sockaddr = res[4]
                    if res[0] == socket.AF_INET:
                        # convert the sockaddr to AF_INET6
                        newhost = '::ffff:' + sockaddr[0]
                        sockaddr = (newhost, sockaddr[1], 0, 0)
                    self.allsockaddrs.append(sockaddr)
                    self.bmc_handlers[sockaddr] = self
                    self.send_data(self.netpacket, sockaddr)
            except socket.gaierror:
                raise exc.IpmiException("Unable to transmit to specified address")
        if retry:
            self.waiting_sessions[self] = {}
            self.waiting_sessions[self]['ipmisession'] = self
            self.waiting_sessions[self]['timeout'] = self.timeout + _monotonic_time() 
Example 50
Project: InsightAgent   Author: insightfinder   File: agentMaster.py    Apache License 2.0 5 votes vote down vote up
def get_ip_address():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    return s.getsockname()[0]