Python socket.recvfrom() Examples

The following are 7 code examples of socket.recvfrom(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: dhcp.py    From python_dhcp_server with MIT License 6 votes vote down vote up
def update(self, timeout = 0):
        try:
            reads = select.select([self.socket], [], [], timeout)[0]
        except ValueError:
            # ValueError: file descriptor cannot be a negative integer (-1)
            return
        for socket in reads:
            try:
                packet = ReadBootProtocolPacket(*socket.recvfrom(4096))
            except OSError:
                # OSError: [WinError 10038] An operation was attempted on something that is not a socket
                pass
            else:
                self.received(packet)
        for transaction_id, transaction in list(self.transactions.items()):
            if transaction.is_done():
                transaction.close()
                self.transactions.pop(transaction_id) 
Example #2
Source File: xiaomihub.py    From aqara-mqtt with Apache License 2.0 6 votes vote down vote up
def _send_socket(self, cmd, rtnCmd, ip, port):
        socket = self._socket
        try:
            _LOGGER.debug('Sending to GW {0}'.format(cmd))
            self._read_unwanted_data()

            socket.settimeout(30.0)
            socket.sendto(cmd.encode(), (ip, port))
            socket.settimeout(30.0)
            data, addr = socket.recvfrom(1024)
            if len(data) is not None:
                resp = json.loads(data.decode())
                _LOGGER.debug('Recieved from GW {0}'.format(resp))
                if resp["cmd"] == rtnCmd:
                    return resp
                else:
                    _LOGGER.error("Response from {0} does not match return cmd".format(ip))
                    _LOGGER.error(data)
            else:
                _LOGGER.error("No response from Gateway")
        except socket.timeout:
            _LOGGER.error("Cannot connect to Gateway")
            socket.close() 
Example #3
Source File: xiaomihub.py    From aqara-mqtt with Apache License 2.0 6 votes vote down vote up
def _listen_to_msg(self):
        while self._listening:
            if self._mcastsocket is not None:
                data, addr = self._mcastsocket.recvfrom(self.SOCKET_BUFSIZE)
                try:
                    data = json.loads(data.decode("ascii"))
                    cmd = data['cmd']
                    _LOGGER.debug(format(data))
                    if cmd == 'heartbeat' and data['model'] == 'gateway':
                        self.GATEWAY_TOKEN = data['token']
                    elif cmd == 'report' or cmd == 'heartbeat':
                        self._queue.put(data)
                    else:
                        _LOGGER.error('Unknown multicast data : {0}'.format(data))
                except Exception as e:
                    raise
                    _LOGGER.error('Cannot process multicast message : {0}'.format(data)) 
Example #4
Source File: sockets.py    From Doga with MIT License 5 votes vote down vote up
def capture(self, sock):
        """ Capture packets in traffic

        param: sock(socket._socketobject): raw socket that listen for traffic
        """

        while True:
            # socket.recvfrom() method returns tuple object
            packet_tuple = sock.recvfrom(65565)
            packet_str = packet_tuple[0]

            self.packet_parser.parse(self.ip, packet_str) 
Example #5
Source File: controller.py    From TobiiGlassesPyController with GNU General Public License v3.0 5 votes vote down vote up
def __discover_device__(self):
		if TOBII_DISCOVERY_ALLOWED == False:
			logging.error("Device discovery is not available due to a missing dependency (netifaces)")
			exit(1)

		logging.debug("Looking for a Tobii Pro Glasses 2 device ...")
		MULTICAST_ADDR = 'ff02::1'
		PORT = 13006

		for i in netifaces.interfaces():
			if netifaces.AF_INET6 in netifaces.ifaddresses(i).keys():
				if "%" in netifaces.ifaddresses(i)[netifaces.AF_INET6][0]['addr']:
					if_name = netifaces.ifaddresses(i)[netifaces.AF_INET6][0]['addr'].split("%")[1]
					if_idx = socket.getaddrinfo(MULTICAST_ADDR + "%" + if_name, PORT, socket.AF_INET6, socket.SOCK_DGRAM)[0][4][3]
					s6 = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
					s6.settimeout(30.0)
					s6.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, if_idx)
					s6.bind(('::', PORT))
					PORT_OUT = PORT if sys.platform == 'win32' or sys.platform == 'darwin' else PORT + 1
					try:
						discover_json = '{"type":"discover"}'
						s6.sendto(discover_json.encode('utf-8'), (MULTICAST_ADDR, PORT_OUT))
						logging.debug("Discover request sent to %s on interface %s " % ( str((MULTICAST_ADDR, PORT_OUT)),if_name) )
						logging.debug("Waiting for a reponse from the device ...")
						data, address = s6.recvfrom(1024)
						jdata = json.loads(data.decode('utf-8'))
						logging.debug("From: " + address[0] + " " + str(data))
						logging.debug("Tobii Pro Glasses found with address: [%s]" % address[0])
						addr = address[0]
						if sys.version_info.major == 3 and sys.version_info.minor >= 8:
							addr = address[0] + '%' + if_name
						return (jdata, addr)
					except:
						logging.debug("No device found on interface %s" % if_name)

		logging.debug("The discovery process did not find any device!")
		return (None, None) 
Example #6
Source File: controller.py    From TobiiGlassesPyController with GNU General Public License v3.0 5 votes vote down vote up
def __grab_data__(self, socket):
		time.sleep(1)
		while self.streaming:
			try:
				data, address = socket.recvfrom(1024)
				jdata = json.loads(data.decode('utf-8'))
				self.__refresh_data__(jdata)
			except socket.timeout:
				logging.error("A timeout occurred while receiving data")
				self.streaming = False 
Example #7
Source File: client_demo.py    From SCUTTLE with MIT License 5 votes vote down vote up
def get(items):

    try:

        message = json.dumps(items).encode('utf-8')         # Take requested data and convert to bytes
        socket.sendto(message, (network.ip,network.port))   # Send data to server
        data, ip = socket.recvfrom(4000)                    # Wait for response, create 4000 byte buffer to store response.
        data = json.loads(data)                             # Take response and convert from bytes to string
        data = dict(zip(items, data))                       # Combine request list with respose list to create dictionary
        return data                                         # Return data

    except Exception as e:

        print(e)
        return 1