Python socket.error() Examples

The following are 50 code examples for showing how to use socket.error(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 7 votes vote down vote up
def setLevel(self, level):
        """Set to new log level.
        """
        self.level = level
        if level <= Logger.DEBUG:
            self.debug = self.log
        else:
            self.debug = self.nolog
        if level <= Logger.WARNING:
            self.warn = self.warning = self.log
        else:
            self.warn = self.warning = self.nolog
        if level <= Logger.INFO:
            self.info = self.log
        else:
            self.info = self.nolog
        if level <= Logger.ERROR:
            self.error = self.log
        else:
            self.error = self.nolog
        if level <= Logger.FATAL:
            self.critical = self.fatal = self.log
        else:
            self.critical = self.fatal = self.nolog 
Example 2
Project: kinect-2-libras   Author: inessadl   File: smtpd.py    (Apache License 2.0) View Source Project 7 votes vote down vote up
def _deliver(self, mailfrom, rcpttos, data):
        import smtplib
        refused = {}
        try:
            s = smtplib.SMTP()
            s.connect(self._remoteaddr[0], self._remoteaddr[1])
            try:
                refused = s.sendmail(mailfrom, rcpttos, data)
            finally:
                s.quit()
        except smtplib.SMTPRecipientsRefused, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients
        except (socket.error, smtplib.SMTPException), e:
            print >> DEBUGSTREAM, 'got', e.__class__
            # All recipients were refused.  If the exception had an associated
            # error code, use it.  Otherwise,fake it with a non-triggering
            # exception code.
            errcode = getattr(e, 'smtp_code', -1)
            errmsg = getattr(e, 'smtp_error', 'ignore')
            for r in rcpttos:
                refused[r] = (errcode, errmsg)
        return refused 
Example 3
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def _socketpair():
                if hasattr(socket, 'socketpair'):
                    return socket.socketpair()
                srv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                srv_sock.bind(('127.0.0.1', 0))
                srv_sock.listen(1)
                write_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                try:
                    write_sock.setblocking(False)
                    try:
                        write_sock.connect(srv_sock.getsockname()[:2])
                    except socket.error as e:
                        if e.args[0] in (EINPROGRESS, EWOULDBLOCK):
                            pass
                        else:
                            raise
                    write_sock.setblocking(True)
                    read_sock = srv_sock.accept()[0]
                except:
                    write_sock.close()
                    raise
                finally:
                    srv_sock.close()
                return (read_sock, write_sock) 
Example 4
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def __init__(self):
                self._poller_name = 'IOCP'
                self.iocp = win32file.CreateIoCompletionPort(win32file.INVALID_HANDLE_VALUE,
                                                             None, 0, 0)
                self._timeouts = []
                self.async_poller = _AsyncPoller(self)
                self.cmd_rsock, self.cmd_wsock = _AsyncPoller._socketpair()
                self.cmd_wsock.setblocking(0)
                self.cmd_rsock = AsyncSocket(self.cmd_rsock)
                self.cmd_rsock._notifier = self
                self.cmd_rsock._register()
                self.cmd_rsock_buf = win32file.AllocateReadBuffer(128)
                self.cmd_rsock._read_overlap.object = self.cmd_rsock_recv
                err, n = win32file.WSARecv(self.cmd_rsock._fileno, self.cmd_rsock_buf,
                                           self.cmd_rsock._read_overlap, 0)
                if err and err != winerror.ERROR_IO_PENDING:
                    logger.warning('WSARecv error: %s', err)
                self._lock = threading.RLock()
                self._polling = False 
Example 5
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def setLevel(self, level):
        """Set to new log level.
        """
        self.level = level
        if level <= Logger.DEBUG:
            self.debug = self.log
        else:
            self.debug = self.nolog
        if level <= Logger.WARNING:
            self.warn = self.warning = self.log
        else:
            self.warn = self.warning = self.nolog
        if level <= Logger.INFO:
            self.info = self.log
        else:
            self.info = self.nolog
        if level <= Logger.ERROR:
            self.error = self.log
        else:
            self.error = self.nolog
        if level <= Logger.FATAL:
            self.critical = self.fatal = self.log
        else:
            self.critical = self.fatal = self.nolog 
Example 6
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def _socketpair():
                if hasattr(socket, 'socketpair'):
                    return socket.socketpair()
                srv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                srv_sock.bind(('127.0.0.1', 0))
                srv_sock.listen(1)
                write_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                try:
                    write_sock.setblocking(False)
                    try:
                        write_sock.connect(srv_sock.getsockname()[:2])
                    except socket.error as e:
                        if e.args[0] in (EINPROGRESS, EWOULDBLOCK):
                            pass
                        else:
                            raise
                    write_sock.setblocking(True)
                    read_sock = srv_sock.accept()[0]
                except:
                    write_sock.close()
                    raise
                finally:
                    srv_sock.close()
                return (read_sock, write_sock) 
Example 7
Project: gluster-georep-tools   Author: aravindavk   File: cli.py    (MIT License) View Source Project 6 votes vote down vote up
def is_port_enabled(hostname, port):
    """
    To check if a port is enabled or not. For example
    To check ssh port is enabled or not,
        is_port_enabled(HOSTNAME, 22)

    To see glusterd port is enabled,
        is_port_enabled(HOSTNAME, 24007)
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((hostname, port))
        enabled = True
    except socket.error:
        enabled = False

    s.close()
    return enabled 
Example 8
Project: PhonePerformanceMeasure   Author: KyleCe   File: FunctionCommon.py    (MIT License) View Source Project 6 votes vote down vote up
def get_my_ip():
    """
    Returns the actual ip of the local machine.
    This code figures out what source address would be used if some traffic
    were to be sent out to some well known address on the Internet. In this
    case, a Google DNS server is used, but the specific address does not
    matter much.  No traffic is actually sent.
    """
    try:
        csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        csock.connect(('8.8.8.8', 80))
        (addr, port) = csock.getsockname()
        csock.close()
        return addr
    except socket.error:
        return "127.0.0.1" 
Example 9
Project: HTP   Author: nklose   File: ChatServer.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def run(self):
        while True:
            try:
                text = irc.recv(2040)
                if text.find('PING') != -1:
                    irc.send('PONG ' + text.split() [1] + '\r\n')
                    connected = True
                elif text.find('PRIVMSG') != -1:
                    end = text.find('!')
                    username = text[1:end]
                    start = text.find(channel + ' :')
                    message = text[start + len(channel) + 2:]
                    log('recv', '<' + username + '> ' + message)
                elif text.find('PART') != -1:
                    end = text.find('!')
                    username = text[1:end]
                    log('recv', '[' + username + '] left \n')
                elif text.find('JOIN') != -1:
                    end = text.find('!')
                    username = text[1:end]
                    log('recv', '[' + username + ']' + ' joined \n')
                else:
                    print(text)
            except socket.error:
                break 
Example 10
Project: Starfish   Author: BillWang139967   File: nbNet_simple.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def accept(self, fd):
        '''??????fd???fd??
        '''
        try:
            # ??fd??????????fd?
            sock_state = self.conn_state[fd]
            # ??sock??????soket?
            sock = sock_state.sock_obj
            # ??accept???????????????????conn?????socket???addr?????????
            conn, addr = sock.accept()
            # ??socket????
            conn.setblocking(0)
            # ?epoll??????socket??fd
            self.epoll_sock.register(conn.fileno(), select.EPOLLIN)
            # ???????conn???????sock
            self.setFd(conn)
            # ????fd????read epoll????????????????
            self.conn_state[conn.fileno()].state = "read"
        except socket.error as msg:
            # ECONNABORTED??TCP???????????RST
            # EAGIIN ???????????????????
            # ????accept
            if msg.args[0] in (errno.ECONNABORTED, errno.EAGAIN):
                return
            raise 
Example 11
Project: Starfish   Author: BillWang139967   File: nbNetBase.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def accept(self, fd):
        '''accpet??epoll?????????
        ??????socket?????
        '''
        logs.dblog("accept: accept client")
        try:
            # ??fd??????????fd?
            sock_state = self.conn_state[fd]
            # ??sock??????soket?
            sock = sock_state.sock_obj
            # ??accept???????????????????conn?????socket???addr?????????
            conn, addr = sock.accept()
            # ??socket????
            conn.setblocking(0)
            # ????????socket??,???IP??
            logs.dblog("accept: find new socket client fd(%s)" % conn.fileno())
            return conn,addr[0]
        except socket.error as msg:
            # EAGIIN ???????????????????(erron???11)
            # ECONNABORTED??TCP???????????RST(erron???103)
            # ????accept ?????? retry
            if msg.errno in (11, 103):
                return "retry" 
Example 12
Project: Starfish   Author: BillWang139967   File: nbNet_simple.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def accept(self, fd):
        '''??????fd???fd??
        '''
        try:
            # ??fd??????????fd?
            sock_state = self.conn_state[fd]
            # ??sock??????soket?
            sock = sock_state.sock_obj
            # ??accept???????????????????conn?????socket???addr?????????
            conn, addr = sock.accept()
            # ??socket????
            conn.setblocking(0)
            # ?epoll??????socket??fd
            self.epoll_sock.register(conn.fileno(), select.EPOLLIN)
            # ???????conn???????sock
            self.setFd(conn)
            # ????fd????read epoll????????????????
            self.conn_state[conn.fileno()].state = "read"
        except socket.error as msg:
            # ECONNABORTED??TCP???????????RST
            # EAGIIN ???????????????????
            # ????accept
            if msg.args[0] in (errno.ECONNABORTED, errno.EAGAIN):
                return
            raise 
Example 13
Project: piksi_ros   Author: uscresl   File: piksi_driver.py    (MIT License) View Source Project 6 votes vote down vote up
def write(self, s):
        return
        """
        Write wrapper.
        Parameters
        ----------
        s : bytes
        Bytes to write
        """
        try:
            self._write_lock.acquire()
            self.handle.sendall(s)
        except socket.error, msg:
            raise IOError
        finally:
            self._write_lock.release()


#
# # Classes for reading/writing observations to serial/udp
# 
Example 14
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def delOSCTarget(self, address, prefix=None):
		"""Delete the specified OSCTarget from the Client's dict.
		the 'address' argument can be a ((host, port) tuple), or a hostname.
		If the 'prefix' argument is given, the Target is only deleted if the address and prefix match.
		"""
		if type(address) in str:
			address = self._searchHostAddr(address) 

		if type(address) == tuple:
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
			
			self._delTarget(address, prefix) 
Example 15
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def hasOSCTarget(self, address, prefix=None):
		"""Return True if the given OSCTarget exists in the Client's dict.
		the 'address' argument can be a ((host, port) tuple), or a hostname.
		If the 'prefix' argument is given, the return-value is only True if the address and prefix match.
		"""
		if type(address) in str:
			address = self._searchHostAddr(address) 

		if type(address) == tuple:
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
			
			if address in list(self.targets.keys()):
				if prefix == None:
					return True
				elif prefix == self.targets[address][0]:
					return True
					
		return False 
Example 16
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def getOSCTarget(self, address):
		"""Returns the OSCTarget matching the given address as a ((host, port), [prefix, filters]) tuple.
		'address' can be a (host, port) tuple, or a 'host' (string), in which case the first matching OSCTarget is returned
		Returns (None, ['',{}]) if address not found.
		"""
		if type(address) in str:
			address = self._searchHostAddr(address) 

		if (type(address) == tuple): 
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
					
			if (address in list(self.targets.keys())):
				try:
					(host, _, _) = socket.gethostbyaddr(host)
				except socket.error:
					pass
	
				return ((host, port), self.targets[address])

		return (None, ['',{}]) 
Example 17
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def _receiveMsg(self):
		""" Receive OSC message from a socket and decode.
		If an error occurs, None is returned, else the message.
		"""
		# get OSC packet size from stream which is prepended each transmission
		chunk = self._receive(4)
		if chunk == None:
			print("SERVER: Socket has been closed.")
			return None
		# extract message length from big endian unsigned long (32 bit) 
		slen = struct.unpack(">L", chunk)[0]
		# receive the actual message
		chunk = self._receive(slen)
		if chunk == None:
			print("SERVER: Socket has been closed.")
			return None
		# decode OSC data and dispatch
		msg = decodeOSC(chunk)
		if msg == None:
			raise OSCError("SERVER: Message decoding failed.")		
		return msg 
Example 18
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def _receiveWithTimeout(self, count):
		chunk = str()
		while len(chunk) < count:
			try:
				tmp = self.socket.recv(count - len(chunk))
			except socket.timeout:
				if not self._running:
					print("CLIENT: Socket timed out and termination requested.")
					return None
				else:
					continue
			except socket.error as e:
				if e[0] == errno.ECONNRESET:
					print("CLIENT: Connection reset by peer.")
					return None
				else:
					raise e
			if not tmp or len(tmp) == 0:
				print("CLIENT: Socket has been closed.")
				return None
			chunk = chunk + tmp
		return chunk 
Example 19
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def _receiveMsgWithTimeout(self):
		""" Receive OSC message from a socket and decode.
		If an error occurs, None is returned, else the message.
		"""
		# get OSC packet size from stream which is prepended each transmission
		chunk = self._receiveWithTimeout(4)
		if not chunk:
			return None
		# extract message length from big endian unsigned long (32 bit) 
		slen = struct.unpack(">L", chunk)[0]
		# receive the actual message
		chunk = self._receiveWithTimeout(slen)
		if not chunk:
			return None
		# decode OSC content
		msg = decodeOSC(chunk)
		if msg == None:
			raise OSCError("CLIENT: Message decoding failed.")
		return msg 
Example 20
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def _transmitWithTimeout(self, data):
		sent = 0
		while sent < len(data):
			try:
				tmp = self.socket.send(data[sent:])
			except socket.timeout:
				if not self._running:
					print("CLIENT: Socket timed out and termination requested.")
					return False
				else:
					continue
			except socket.error as e:
				if e[0] == errno.ECONNRESET:
					print("CLIENT: Connection reset by peer.")
					return False
				else:
					raise e
			if tmp == 0:
				return False
			sent += tmp
		return True 
Example 21
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def hasOSCTarget(self, address, prefix=None):
		"""Return True if the given OSCTarget exists in the Client's dict.
		the 'address' argument can be a ((host, port) tuple), or a hostname.
		If the 'prefix' argument is given, the return-value is only True if the address and prefix match.
		"""
		if type(address) in types.StringTypes:
			address = self._searchHostAddr(address) 

		if type(address) == types.TupleType:
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
			
			if address in self.targets.keys():
				if prefix == None:
					return True
				elif prefix == self.targets[address][0]:
					return True
					
		return False 
Example 22
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def getOSCTarget(self, address):
		"""Returns the OSCTarget matching the given address as a ((host, port), [prefix, filters]) tuple.
		'address' can be a (host, port) tuple, or a 'host' (string), in which case the first matching OSCTarget is returned
		Returns (None, ['',{}]) if address not found.
		"""
		if type(address) in types.StringTypes:
			address = self._searchHostAddr(address) 

		if (type(address) == types.TupleType): 
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
					
			if (address in self.targets.keys()):
				try:
					(host, _, _) = socket.gethostbyaddr(host)
				except socket.error:
					pass
	
				return ((host, port), self.targets[address])

		return (None, ['',{}]) 
Example 23
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def _transmitMsg(self, msg):
		"""Send an OSC message over a streaming socket. Raises exception if it
		should fail. If everything is transmitted properly, True is returned. If
		socket has been closed, False.
		"""
		if not isinstance(msg, OSCMessage):
			raise TypeError("'msg' argument is not an OSCMessage or OSCBundle object")

		try:
			binary = msg.getBinary()
			length = len(binary)
			# prepend length of packet before the actual message (big endian)
			len_big_endian = array.array('c', '\0' * 4)
			struct.pack_into(">L", len_big_endian, 0, length)
			len_big_endian = len_big_endian.tostring()
			if self._transmit(len_big_endian) and self._transmit(binary):
				return True
			return False			
		except socket.error, e:
			if e[0] == errno.EPIPE: # broken pipe
				return False
			raise e 
Example 24
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def _receiveWithTimeout(self, count):
		chunk = str()
		while len(chunk) < count:
			try:
				tmp = self.socket.recv(count - len(chunk))
			except socket.timeout:
				if not self._running:
					print "CLIENT: Socket timed out and termination requested."
					return None
				else:
					continue
			except socket.error, e:
				if e[0] == errno.ECONNRESET:
					print "CLIENT: Connection reset by peer."
					return None
				else:
					raise e
			if not tmp or len(tmp) == 0:
				print "CLIENT: Socket has been closed."
				return None
			chunk = chunk + tmp
		return chunk 
Example 25
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def _receiveMsgWithTimeout(self):
		""" Receive OSC message from a socket and decode.
		If an error occurs, None is returned, else the message.
		"""
		# get OSC packet size from stream which is prepended each transmission
		chunk = self._receiveWithTimeout(4)
		if not chunk:
			return None
		# extract message length from big endian unsigned long (32 bit) 
		slen = struct.unpack(">L", chunk)[0]
		# receive the actual message
		chunk = self._receiveWithTimeout(slen)
		if not chunk:
			return None
		# decode OSC content
		msg = decodeOSC(chunk)
		if msg == None:
			raise OSCError("CLIENT: Message decoding failed.")
		return msg 
Example 26
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def _transmitWithTimeout(self, data):
		sent = 0
		while sent < len(data):
			try:
				tmp = self.socket.send(data[sent:])
			except socket.timeout:
				if not self._running:
					print "CLIENT: Socket timed out and termination requested."
					return False
				else:
					continue
			except socket.error, e:
				if e[0] == errno.ECONNRESET:
					print "CLIENT: Connection reset by peer."
					return False
				else:
					raise e
			if tmp == 0:
				return False
			sent += tmp
		return True 
Example 27
Project: python-   Author: secondtonone1   File: pyopenssl.py    (license) View Source Project 6 votes vote down vote up
def recv(self, *args, **kwargs):
        try:
            data = self.connection.recv(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return b''
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return b''
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd, wd, ed = select.select(
                [self.socket], [], [], self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv(*args, **kwargs)
        else:
            return data 
Example 28
Project: python-   Author: secondtonone1   File: pyopenssl.py    (license) View Source Project 6 votes vote down vote up
def recv_into(self, *args, **kwargs):
        try:
            return self.connection.recv_into(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return 0
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return 0
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd, wd, ed = select.select(
                [self.socket], [], [], self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv_into(*args, **kwargs) 
Example 29
Project: python-   Author: secondtonone1   File: utils.py    (license) View Source Project 6 votes vote down vote up
def is_valid_cidr(string_network):
    """
    Very simple check of the cidr format in no_proxy variable.

    :rtype: bool
    """
    if string_network.count('/') == 1:
        try:
            mask = int(string_network.split('/')[1])
        except ValueError:
            return False

        if mask < 1 or mask > 32:
            return False

        try:
            socket.inet_aton(string_network.split('/')[0])
        except socket.error:
            return False
    else:
        return False
    return True 
Example 30
Project: ironic-staging-drivers   Author: openstack   File: power.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def reboot(self, task):
        """Not supported. Cycles the power to the task's node.

        This operation is not fully supported by the Wake-On-Lan
        driver. So this method will just try to power the task's node on.

        :param task: a TaskManager instance containing the node to act on.
        :raises: InvalidParameterValue if parameters are invalid.
        :raises: MissingParameterValue if required parameters are missing.
        :raises: WOLOperationError if an error occur when sending the
            magic packets

        """
        LOG.info('Reboot called for node %s. Wake-On-Lan does '
                 'not fully support this operation. Trying to '
                 'power on the node.', task.node.uuid)
        self.set_power_state(task, states.POWER_ON) 
Example 31
Project: IotCenter   Author: panjanek   File: iotcommon.py    (MIT License) View Source Project 6 votes vote down vote up
def handle(self):
        try:
            data = self.request[0]
            clientAddr = self.client_address;
            self.logger.debug("UDP packet from {0}:{1}, length {2}".format(clientAddr[0], clientAddr[1], len(data)))
            self.logger.debug("message hex   : %s", binascii.hexlify(data))
            if data[0:4] == "IOT\xff":    
                self.logger.debug("heartbeat packet - ignoring")      
            elif data[0:4] == "IOT\0" and len(data)>=88 and ((len(data)-72)%16) == 0:    
                self.handleIotPacket(data, clientAddr)        
            else:
                self.logger.warning("unknown packet - ignoring")      
        except Exception as e: 
            self.logger.exception(e)
        except:   
            self.logger.error("error on handling incomming packet: {0} ".format(sys.exc_info()[0])) 
Example 32
Project: my-first-blog   Author: AnkurBegining   File: pyopenssl.py    (license) View Source Project 6 votes vote down vote up
def recv(self, *args, **kwargs):
        try:
            data = self.connection.recv(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return b''
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return b''
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd = util.wait_for_read(self.socket, self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv(*args, **kwargs)
        else:
            return data 
Example 33
Project: my-first-blog   Author: AnkurBegining   File: pyopenssl.py    (license) View Source Project 6 votes vote down vote up
def recv_into(self, *args, **kwargs):
        try:
            return self.connection.recv_into(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return 0
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return 0
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd = util.wait_for_read(self.socket, self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv_into(*args, **kwargs) 
Example 34
Project: my-first-blog   Author: AnkurBegining   File: selectors.py    (license) View Source Project 6 votes vote down vote up
def unregister(self, fileobj):
        """ Unregister a file object from being monitored. """
        try:
            key = self._fd_to_key.pop(self._fileobj_lookup(fileobj))
        except KeyError:
            raise KeyError("{0!r} is not registered".format(fileobj))

        # Getting the fileno of a closed socket on Windows errors with EBADF.
        except socket.error as e:  # Platform-specific: Windows.
            if e.errno != errno.EBADF:
                raise
            else:
                for key in self._fd_to_key.values():
                    if key.fileobj is fileobj:
                        self._fd_to_key.pop(key.fd)
                        break
                else:
                    raise KeyError("{0!r} is not registered".format(fileobj))
        return key 
Example 35
Project: my-first-blog   Author: AnkurBegining   File: pyopenssl.py    (license) View Source Project 6 votes vote down vote up
def recv(self, *args, **kwargs):
        try:
            data = self.connection.recv(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return b''
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return b''
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd, wd, ed = select.select(
                [self.socket], [], [], self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv(*args, **kwargs)
        else:
            return data 
Example 36
Project: my-first-blog   Author: AnkurBegining   File: pyopenssl.py    (license) View Source Project 6 votes vote down vote up
def recv_into(self, *args, **kwargs):
        try:
            return self.connection.recv_into(*args, **kwargs)
        except OpenSSL.SSL.SysCallError as e:
            if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
                return 0
            else:
                raise SocketError(str(e))
        except OpenSSL.SSL.ZeroReturnError as e:
            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
                return 0
            else:
                raise
        except OpenSSL.SSL.WantReadError:
            rd, wd, ed = select.select(
                [self.socket], [], [], self.socket.gettimeout())
            if not rd:
                raise timeout('The read operation timed out')
            else:
                return self.recv_into(*args, **kwargs) 
Example 37
Project: my-first-blog   Author: AnkurBegining   File: utils.py    (license) View Source Project 6 votes vote down vote up
def is_valid_cidr(string_network):
    """
    Very simple check of the cidr format in no_proxy variable.

    :rtype: bool
    """
    if string_network.count('/') == 1:
        try:
            mask = int(string_network.split('/')[1])
        except ValueError:
            return False

        if mask < 1 or mask > 32:
            return False

        try:
            socket.inet_aton(string_network.split('/')[0])
        except socket.error:
            return False
    else:
        return False
    return True 
Example 38
Project: my-first-blog   Author: AnkurBegining   File: utils.py    (license) View Source Project 6 votes vote down vote up
def is_valid_cidr(string_network):
    """
    Very simple check of the cidr format in no_proxy variable.

    :rtype: bool
    """
    if string_network.count('/') == 1:
        try:
            mask = int(string_network.split('/')[1])
        except ValueError:
            return False

        if mask < 1 or mask > 32:
            return False

        try:
            socket.inet_aton(string_network.split('/')[0])
        except socket.error:
            return False
    else:
        return False
    return True 
Example 39
Project: tornetcd   Author: mqingyn   File: client.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def search_machine(self, callback=None):
        uri = self._base_url + self.version_prefix + '/machines'
        req = HTTPRequest(uri, self._MGET, request_timeout=self.read_timeout,
                          follow_redirects=self.allow_redirect, )
        response_future = self.http.fetch(req, callback=lambda result: result)

        def _callback(fut):
            exc = fut.exc_info()
            if exc:
                if not isinstance(exc[1], etcdexcept.EtcdException):
                    # We can't get the list of machines, if one server is in the
                    # machines cache, try on it
                    _log.error("Failed to get list of machines from %s%s: %r and retry it.",
                               uri, self.version_prefix, exc)
                    if self._machines_cache:
                        self._base_url = self._machines_cache.pop(0)
                        _log.debug("Retrying on %s", self._base_url)
                        # Call myself
                        self.ioloop.add_future(self.search_machine(), _callback)
                        return
                    else:
                        raise etcdexcept.EtcdException("Could not get the list of servers, "
                                                       "maybe you provided the wrong "
                                                       "host(s) to connect to?")
            else:
                response = fut.result()
                machines = [
                    node.strip() for node in
                    self._handle_server_response(response).body.decode('utf-8').split(',')
                    ]
                _log.debug("Retrieved list of machines: %s", machines)
                self._machines_cache = machines
                if self._base_url not in self._machines_cache:
                    self._base_url = self._choice_machine()
            callback(fut.result())

        self.ioloop.add_future(response_future, _callback) 
Example 40
Project: tornetcd   Author: mqingyn   File: client.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def _check_cluster_id(self, response):
        cluster_id = response.headers.get("x-etcd-cluster-id")
        if not cluster_id:
            _log.warning("etcd response did not contain a cluster ID")
            return
        id_changed = (self.expected_cluster_id and
                      cluster_id != self.expected_cluster_id)
        # Update the ID so we only raise the exception once.
        old_expected_cluster_id = self.expected_cluster_id
        self.expected_cluster_id = cluster_id
        if id_changed:
            # Defensive: clear the pool so that we connect afresh next
            # time.
            self._base_url = self._choice_machine()
            _log.error(
                    'The UUID of the cluster changed from {} to '
                    '{}.'.format(old_expected_cluster_id, cluster_id)) 
Example 41
Project: gimel   Author: Alephbet   File: connection.py    (MIT License) View Source Project 6 votes vote down vote up
def send_packed_command(self, command):
        "Send an already packed command to the Redis server"
        if not self._sock:
            self.connect()
        try:
            if isinstance(command, str):
                command = [command]
            for item in command:
                self._sock.sendall(item)
        except socket.timeout:
            self.disconnect()
            raise TimeoutError("Timeout writing to socket")
        except socket.error:
            e = sys.exc_info()[1]
            self.disconnect()
            if len(e.args) == 1:
                errno, errmsg = 'UNKNOWN', e.args[0]
            else:
                errno = e.args[0]
                errmsg = e.args[1]
            raise ConnectionError("Error %s while writing to socket. %s." %
                                  (errno, errmsg))
        except:
            self.disconnect()
            raise 
Example 42
Project: kinect-2-libras   Author: inessadl   File: SocketServer.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _handle_request_noblock(self):
        """Handle one request, without blocking.

        I assume that select.select has returned that the socket is
        readable before this function was called, so there should be
        no risk of blocking in get_request().
        """
        try:
            request, client_address = self.get_request()
        except socket.error:
            return
        if self.verify_request(request, client_address):
            try:
                self.process_request(request, client_address)
            except:
                self.handle_error(request, client_address)
                self.shutdown_request(request) 
Example 43
Project: kinect-2-libras   Author: inessadl   File: SocketServer.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def shutdown_request(self, request):
        """Called to shutdown and close an individual request."""
        try:
            #explicitly shutdown.  socket.close() merely releases
            #the socket and waits for GC to perform the actual close.
            request.shutdown(socket.SHUT_WR)
        except socket.error:
            pass #some platforms may raise ENOTCONN here
        self.close_request(request) 
Example 44
Project: kinect-2-libras   Author: inessadl   File: imaplib.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def xatom(self, name, *args):
        """Allow simple extension commands
                notified by server in CAPABILITY response.

        Assumes command is legal in current state.

        (typ, [data]) = <instance>.xatom(name, arg, ...)

        Returns response appropriate to extension command `name'.
        """
        name = name.upper()
        #if not name in self.capabilities:      # Let the server decide!
        #    raise self.error('unknown extension command: %s' % name)
        if not name in Commands:
            Commands[name] = (self.state,)
        return self._simple_command(name, *args)



    #       Private methods 
Example 45
Project: kinect-2-libras   Author: inessadl   File: imaplib.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _get_line(self):

        line = self.readline()
        if not line:
            raise self.abort('socket error: EOF')

        # Protocol mandates all lines terminated by CRLF
        if not line.endswith('\r\n'):
            raise self.abort('socket error: unterminated line')

        line = line[:-2]
        if __debug__:
            if self.debug >= 4:
                self._mesg('< %s' % line)
            else:
                self._log('< %s' % line)
        return line 
Example 46
Project: kinect-2-libras   Author: inessadl   File: smtplib.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def connect(self, host='localhost', port=0):
        """Connect to the LMTP daemon, on either a Unix or a TCP socket."""
        if host[0] != '/':
            return SMTP.connect(self, host, port)

        # Handle Unix-domain sockets.
        try:
            self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.sock.connect(host)
        except socket.error, msg:
            if self.debuglevel > 0:
                print>>stderr, 'connect fail:', host
            if self.sock:
                self.sock.close()
            self.sock = None
            raise socket.error, msg
        (code, msg) = self.getreply()
        if self.debuglevel > 0:
            print>>stderr, "connect:", msg
        return (code, msg)


# Test the sendmail method, which tests most of the others.
# Note: This always sends to localhost. 
Example 47
Project: kinect-2-libras   Author: inessadl   File: ssl.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _real_connect(self, addr, return_errno):
        # Here we assume that the socket is client-side, and not
        # connected at the time of the call.  We connect it, then wrap it.
        if self._connected:
            raise ValueError("attempt to connect already-connected SSLSocket!")
        self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile,
                                    self.cert_reqs, self.ssl_version,
                                    self.ca_certs, self.ciphers)
        try:
            socket.connect(self, addr)
            if self.do_handshake_on_connect:
                self.do_handshake()
        except socket_error as e:
            if return_errno:
                return e.errno
            else:
                self._sslobj = None
                raise e
        self._connected = True
        return 0 
Example 48
Project: kinect-2-libras   Author: inessadl   File: ssl.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def sslwrap_simple(sock, keyfile=None, certfile=None):

    """A replacement for the old socket.ssl function.  Designed
    for compability with Python 2.5 and earlier.  Will disappear in
    Python 3.0."""

    if hasattr(sock, "_sock"):
        sock = sock._sock

    ssl_sock = _ssl.sslwrap(sock, 0, keyfile, certfile, CERT_NONE,
                            PROTOCOL_SSLv23, None)
    try:
        sock.getpeername()
    except socket_error:
        # no, no connection yet
        pass
    else:
        # yes, do the handshake
        ssl_sock.do_handshake()

    return ssl_sock 
Example 49
Project: kinect-2-libras   Author: inessadl   File: urllib2.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def error(self, proto, *args):
        if proto in ('http', 'https'):
            # XXX http[s] protocols are special-cased
            dict = self.handle_error['http'] # https is not different than http
            proto = args[2]  # YUCK!
            meth_name = 'http_error_%s' % proto
            http_err = 1
            orig_args = args
        else:
            dict = self.handle_error
            meth_name = proto + '_error'
            http_err = 0
        args = (dict, proto, meth_name) + args
        result = self._call_chain(*args)
        if result:
            return result

        if http_err:
            args = (dict, 'default', 'http_error_default') + orig_args
            return self._call_chain(*args)

# XXX probably also want an abstract factory that knows when it makes
# sense to skip a superclass in favor of a subclass and when it might
# make sense to include both 
Example 50
Project: kinect-2-libras   Author: inessadl   File: handlers.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def __init__(self, host, port):
        """
        Initializes the handler with a specific host address and port.

        The attribute 'closeOnError' is set to 1 - which means that if
        a socket error occurs, the socket is silently closed and then
        reopened on the next logging call.
        """
        logging.Handler.__init__(self)
        self.host = host
        self.port = port
        self.sock = None
        self.closeOnError = 0
        self.retryTime = None
        #
        # Exponential backoff parameters.
        #
        self.retryStart = 1.0
        self.retryMax = 30.0
        self.retryFactor = 2.0