Python socket.SO_ERROR Examples

The following are 30 code examples of socket.SO_ERROR(). 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: _socketcan.py    From pyuavcan with MIT License 9 votes vote down vote up
def _make_socket(iface_name: str, can_fd: bool) -> socket.SocketType:
    s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
    try:
        s.bind((iface_name,))
        s.setsockopt(socket.SOL_SOCKET, _SO_TIMESTAMP, 1)  # timestamping
        if can_fd:
            s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FD_FRAMES, 1)

        s.setblocking(False)

        if 0 != s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR):
            raise OSError('Could not configure the socket: getsockopt(SOL_SOCKET, SO_ERROR) != 0')
    except BaseException:
        with contextlib.suppress(Exception):
            s.close()
        raise

    return s 
Example #2
Source File: iostream.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def _handle_connect(self):
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            gen_log.warning("Connect error on fd %d: %s",
                            self.socket.fileno(), errno.errorcode[err])
            self.close()
            return
        if self._connect_callback is not None:
            callback = self._connect_callback
            self._connect_callback = None
            self._run_callback(callback)
        self._connecting = False 
Example #3
Source File: iostream.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def _handle_connect(self):
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            gen_log.warning("Connect error on fd %d: %s",
                            self.socket.fileno(), errno.errorcode[err])
            self.close()
            return
        if self._connect_callback is not None:
            callback = self._connect_callback
            self._connect_callback = None
            self._run_callback(callback)
        self._connecting = False 
Example #4
Source File: handlers.py    From oss-ftp with MIT License 6 votes vote down vote up
def handle_connect(self):
        """Called when connection is established."""
        self.del_channel()
        if self._idler is not None and not self._idler.cancelled:
            self._idler.cancel()
        if not self.cmd_channel.connected:
            return self.close()
        # fix for asyncore on python < 2.6, meaning we aren't
        # actually connected.
        # test_active_conn_error tests this condition
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            raise socket.error(err)
        #
        msg = 'Active data connection established.'
        self.cmd_channel.respond('200 ' + msg)
        self.cmd_channel.log_cmd(self._cmd, self._normalized_addr, 200, msg)
        #
        if not self.cmd_channel.connected:
            return self.close()
        # delegate such connection to DTP handler
        handler = self.cmd_channel.dtp_handler(self.socket, self.cmd_channel)
        self.cmd_channel.data_channel = handler
        self.cmd_channel._on_dtp_connection() 
Example #5
Source File: handlers.py    From oss-ftp with MIT License 6 votes vote down vote up
def handle_connect(self):
        """Called when connection is established."""
        self.del_channel()
        if self._idler is not None and not self._idler.cancelled:
            self._idler.cancel()
        if not self.cmd_channel.connected:
            return self.close()
        # fix for asyncore on python < 2.6, meaning we aren't
        # actually connected.
        # test_active_conn_error tests this condition
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            raise socket.error(err)
        #
        msg = 'Active data connection established.'
        self.cmd_channel.respond('200 ' + msg)
        self.cmd_channel.log_cmd(self._cmd, self._normalized_addr, 200, msg)
        #
        if not self.cmd_channel.connected:
            return self.close()
        # delegate such connection to DTP handler
        handler = self.cmd_channel.dtp_handler(self.socket, self.cmd_channel)
        self.cmd_channel.data_channel = handler
        self.cmd_channel._on_dtp_connection() 
Example #6
Source File: asyncadapter.py    From plex-for-kodi with GNU General Public License v2.0 6 votes vote down vote up
def _connect(self, sock, sa):
        while not self._canceled and not ABORT_FLAG_FUNCTION():
            time.sleep(0.01)
            self._check_timeout()  # this should be done at the beginning of each loop
            status = sock.connect_ex(sa)
            if not status or status in (errno.EISCONN, WIN_EISCONN):
                break
            elif status in (errno.EINPROGRESS, WIN_EWOULDBLOCK):
                self.deadline = time.time() + self._timeout.getConnectTimeout()
            # elif status in (errno.EWOULDBLOCK, errno.EALREADY) or (os.name == 'nt' and status == errno.WSAEINVAL):
            #     pass
            yield

        if self._canceled or ABORT_FLAG_FUNCTION():
            raise CanceledException('Request canceled')

        error = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if error:
            # TODO: determine when this case can actually happen
            raise socket.error((error,)) 
Example #7
Source File: linux.py    From wstan with MIT License 6 votes vote down vote up
def _sock_connect_tfo_cb(self, fut, sock, address, dat):
        if fut.cancelled():
            return

        try:
            err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
            if err != 0:
                raise OSError(err, 'ConnectTfo failed %s' % (address,))  # Jump to any except clause below.
        except (BlockingIOError, InterruptedError):
            # socket is still registered, the callback will be retried later
            pass
        except Exception as exc:
            fut.set_exception(exc)
        else:
            if dat:
                self._sock_sendall(fut, False, sock, dat)
            else:
                fut.set_result(None) 
Example #8
Source File: tcp.py    From bacpypes with MIT License 6 votes vote down vote up
def handle_connect_event(self):
        if _debug: TCPClient._debug("handle_connect_event")

        # there might be an error
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if _debug: TCPClient._debug("    - err: %r", err)

        # check for connection refused
        if (err == 0):
            if _debug: TCPClient._debug("    - no error")
            self.connected = True
        elif (err == errno.ECONNREFUSED):
            if _debug: TCPClient._debug("    - connection to %r refused", self.peer)
            self.handle_error(socket.error(errno.ECONNREFUSED, "connection refused"))
            return

        # pass along
        asyncore.dispatcher.handle_connect_event(self) 
Example #9
Source File: iostream.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
def _handle_connect(self):
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            #logging.warning("Connect error on fd %d: %s",
            #                self.socket.fileno(), errno.errorcode[err])
            ht.logger.warning("Connect error on fd %d: %s",
                            self.socket.fileno(), errno.errorcode[err])
            self.close()
            return
        if self._connect_callback is not None:
            callback = self._connect_callback
            self._connect_callback = None
            self._run_callback(callback)
        self._connecting = False 
Example #10
Source File: tcp.py    From bacpypes with MIT License 6 votes vote down vote up
def handle_connect_event(self):
        if _debug: TCPClient._debug("handle_connect_event")

        # there might be an error
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if _debug: TCPClient._debug("    - err: %r", err)

        # check for connection refused
        if (err == 0):
            if _debug: TCPClient._debug("    - no error")
            self.connected = True
        elif (err == errno.ECONNREFUSED):
            if _debug: TCPClient._debug("    - connection to %r refused", self.peer)
            self.handle_error(socket.error(errno.ECONNREFUSED, "connection refused"))
            return

        # pass along
        asyncore.dispatcher.handle_connect_event(self) 
Example #11
Source File: selector_events.py    From Imogen with MIT License 6 votes vote down vote up
def _sock_connect_cb(self, fut, sock, address):
        if fut.cancelled():
            return

        try:
            err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
            if err != 0:
                # Jump to any except clause below.
                raise OSError(err, f'Connect call failed {address}')
        except (BlockingIOError, InterruptedError):
            # socket is still registered, the callback will be retried later
            pass
        except Exception as exc:
            fut.set_exception(exc)
        else:
            fut.set_result(None) 
Example #12
Source File: tcp.py    From bacpypes with MIT License 6 votes vote down vote up
def handle_connect_event(self):
        if _debug: TCPClient._debug("handle_connect_event")

        # there might be an error
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if _debug: TCPClient._debug("    - err: %r", err)

        # check for connection refused
        if (err == 0):
            if _debug: TCPClient._debug("    - no error")
        elif (err == 111):
            if _debug: TCPClient._debug("    - connection to %r refused", self.peer)
            self.handle_error(socket.error(111, "connection refused"))
            return

        # pass along
        asyncore.dispatcher.handle_connect_event(self) 
Example #13
Source File: handlers.py    From script-languages with MIT License 6 votes vote down vote up
def handle_connect(self):
        """Called when connection is established."""
        self.del_channel()
        if self._idler is not None and not self._idler.cancelled:
            self._idler.cancel()
        if not self.cmd_channel.connected:
            return self.close()
        # fix for asyncore on python < 2.6, meaning we aren't
        # actually connected.
        # test_active_conn_error tests this condition
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            raise socket.error(err)
        #
        msg = 'Active data connection established.'
        self.cmd_channel.respond('200 ' + msg)
        self.cmd_channel.log_cmd(self._cmd, self._normalized_addr, 200, msg)
        #
        if not self.cmd_channel.connected:
            return self.close()
        # delegate such connection to DTP handler
        handler = self.cmd_channel.dtp_handler(self.socket, self.cmd_channel)
        self.cmd_channel.data_channel = handler
        self.cmd_channel._on_dtp_connection() 
Example #14
Source File: selector_events.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def _sock_connect_cb(self, fut, sock, address):
        if fut.cancelled():
            return

        try:
            err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
            if err != 0:
                # Jump to any except clause below.
                raise OSError(err, 'Connect call failed %s' % (address,))
        except (BlockingIOError, InterruptedError):
            # socket is still registered, the callback will be retried later
            pass
        except Exception as exc:
            fut.set_exception(exc)
        else:
            fut.set_result(None) 
Example #15
Source File: iostream.py    From tornado-zh with MIT License 6 votes vote down vote up
def _handle_connect(self):
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            if self._connect_future is None:
                gen_log.warning("Connect error on fd %s: %s",
                                self.socket.fileno(), errno.errorcode[err])
            self.close()
            return
        if self._connect_callback is not None:
            callback = self._connect_callback
            self._connect_callback = None
            self._run_callback(callback)
        if self._connect_future is not None:
            future = self._connect_future
            self._connect_future = None
            future.set_result(self)
        self._connecting = False 
Example #16
Source File: selector_events.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def _sock_connect_cb(self, fut, sock, address):
        if fut.cancelled():
            return

        try:
            err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
            if err != 0:
                # Jump to any except clause below.
                raise OSError(err, 'Connect call failed %s' % (address,))
        except (BlockingIOError, InterruptedError):
            # socket is still registered, the callback will be retried later
            pass
        except Exception as exc:
            fut.set_exception(exc)
        else:
            fut.set_result(None) 
Example #17
Source File: iostream.py    From tornado-zh with MIT License 6 votes vote down vote up
def _handle_connect(self):
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            if self._connect_future is None:
                gen_log.warning("Connect error on fd %s: %s",
                                self.socket.fileno(), errno.errorcode[err])
            self.close()
            return
        if self._connect_callback is not None:
            callback = self._connect_callback
            self._connect_callback = None
            self._run_callback(callback)
        if self._connect_future is not None:
            future = self._connect_future
            self._connect_future = None
            future.set_result(self)
        self._connecting = False 
Example #18
Source File: tcp_connection.py    From PySyncObj with MIT License 5 votes vote down vote up
def __processRead(self):
        try:
            incoming = self.__socket.recv(self.__recvBufferSize)
        except socket.error as e:
            if e.errno not in (socket.errno.EAGAIN, socket.errno.EWOULDBLOCK):
                self.disconnect()
            return False
        if self.__socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR):
            self.disconnect()
            return False
        if not incoming:
            self.disconnect()
            return False
        self.__readBuffer += incoming
        return True 
Example #19
Source File: tcp.py    From bacpypes with MIT License 5 votes vote down vote up
def handle_write_event(self):
        if _debug: TCPClient._debug("handle_write_event")

        # there might be an error
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if _debug: TCPClient._debug("    - err: %r", err)

        # check for connection refused
        if err == 0:
            if not self.connected:
                if _debug: TCPClient._debug("    - connected")
                self.handle_connect()
        else:
            if _debug: TCPClient._debug("    - peer: %r", self.peer)

            if (err == errno.ECONNREFUSED):
                socket_error = socket.error(err, "connection refused")
            elif (err == errno.ETIMEDOUT):
                socket_error = socket.error(err, "timed out")
            elif (err == errno.EHOSTUNREACH):
                socket_error = socket.error(err, "host unreachable")
            else:
                socket_error = socket.error(err, "other unknown: %r" % (err,))
            if _debug: TCPClient._debug("    - socket_error: %r", socket_error)

            self.handle_error(socket_error)
            return

        # pass along
        asyncore.dispatcher.handle_write_event(self) 
Example #20
Source File: asyncore.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def getsockopt(self, level, optname, buflen=None):
            if (level == socket.SOL_SOCKET and
                optname == socket.SO_ERROR and
                not buflen):
                return 0
            raise NotImplementedError("Only asyncore specific behaviour "
                                      "implemented.") 
Example #21
Source File: eventloop.py    From shadowsocks with Apache License 2.0 5 votes vote down vote up
def get_sock_error(sock):
    error_number = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
    return socket.error(error_number, os.strerror(error_number)) 
Example #22
Source File: glib_events.py    From pychess with GNU General Public License v3.0 5 votes vote down vote up
def _socket_handle_errors(self, sock):
        """Raise exceptions for error states (SOL_ERROR) on the given socket object."""
        errno = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if errno != 0:
            if sys.platform == "win32":
                msg = socket.errorTab.get(errno, "Error {0}".format(errno))
                raise OSError(errno, "[WinError {0}] {1}".format(errno, msg), None, errno)
            else:
                raise OSError(errno, os.strerror(errno))

    ###############################
    # Low-level socket operations #
    ############################### 
Example #23
Source File: eventloop.py    From ShadowsocksFork with Apache License 2.0 5 votes vote down vote up
def get_sock_error(sock):
    error_number = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
    return socket.error(error_number, os.strerror(error_number)) 
Example #24
Source File: find_service.py    From w9scan with GNU General Public License v2.0 5 votes vote down vote up
def scanPort(host, ports, timeout):
    portList = []
    sockList = set()
    while len(ports):
        socketObj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socketObj.setblocking(0)
        socketObj.connect_ex((host, ports.pop()))
        sockList.add(socketObj)
        if len(sockList) < 200 and len(ports) > 0:
            continue
        start_time = time.time()
        try:
            while True:
                # readable,writeable,exceptional
                readable, writeable, exceptional = select.select([], sockList, [], 0.5)
                if len(writeable) > 0:
                    for socketObj in writeable:
                        strtus = socketObj.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
                        if strtus == 0:
                            host, port = socketObj.getpeername()
                            portList.append(port)
                        socketObj.close()

                    sockList = sockList - set(writeable)
                if time.time() - start_time > timeout:
                    break
        except:
            pass

        sockList = set()

    portList.sort()
    return portList 
Example #25
Source File: asyncore.py    From Imogen with MIT License 5 votes vote down vote up
def getsockopt(self, level, optname, buflen=None):
            if (level == socket.SOL_SOCKET and
                optname == socket.SO_ERROR and
                not buflen):
                return 0
            raise NotImplementedError("Only asyncore specific behaviour "
                                      "implemented.") 
Example #26
Source File: asyncore.py    From Imogen with MIT License 5 votes vote down vote up
def handle_expt_event(self):
        # handle_expt_event() is called if there might be an error on the
        # socket, or if there is OOB data
        # check for the error condition first
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            # we can get here when select.select() says that there is an
            # exceptional condition on the socket
            # since there is an error, we'll go ahead and close the socket
            # like we would in a subclassed handle_read() that received no
            # data
            self.handle_close()
        else:
            self.handle_expt() 
Example #27
Source File: asyncore.py    From Imogen with MIT License 5 votes vote down vote up
def handle_connect_event(self):
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            raise OSError(err, _strerror(err))
        self.handle_connect()
        self.connected = True
        self.connecting = False 
Example #28
Source File: iostream.py    From pySINDy with MIT License 5 votes vote down vote up
def _handle_connect(self):
        try:
            err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        except socket.error as e:
            # Hurd doesn't allow SO_ERROR for loopback sockets because all
            # errors for such sockets are reported synchronously.
            if errno_from_exception(e) == errno.ENOPROTOOPT:
                err = 0
        if err != 0:
            self.error = socket.error(err, os.strerror(err))
            # IOLoop implementations may vary: some of them return
            # an error state before the socket becomes writable, so
            # in that case a connection failure would be handled by the
            # error path in _handle_events instead of here.
            if self._connect_future is None:
                gen_log.warning("Connect error on fd %s: %s",
                                self.socket.fileno(), errno.errorcode[err])
            self.close()
            return
        if self._connect_callback is not None:
            callback = self._connect_callback
            self._connect_callback = None
            self._run_callback(callback)
        if self._connect_future is not None:
            future = self._connect_future
            self._connect_future = None
            future.set_result(self)
        self._connecting = False 
Example #29
Source File: iostream.py    From pySINDy with MIT License 5 votes vote down vote up
def get_fd_error(self):
        errno = self.socket.getsockopt(socket.SOL_SOCKET,
                                       socket.SO_ERROR)
        return socket.error(errno, os.strerror(errno)) 
Example #30
Source File: ftpserver.py    From script-languages with MIT License 5 votes vote down vote up
def handle_connect(self):
        """Called when connection is established."""
        if self._idler is not None and not self._idler.cancelled:
            self._idler.cancel()
        if not self.cmd_channel.connected:
            return self.close()
        # fix for asyncore on python < 2.6, meaning we aren't
        # actually connected.
        # test_active_conn_error tests this condition
        err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if err != 0:
            raise socket.error(err)
        #
        msg = 'Active data connection established.'
        self.cmd_channel.respond('200 ' + msg)
        self.cmd_channel.log_cmd(self._cmd, self._normalized_addr, 200, msg)
        #
        if not self.cmd_channel.connected:
            return self.close()
        # delegate such connection to DTP handler
        handler = self.cmd_channel.dtp_handler(self.socket, self.cmd_channel)
        self.cmd_channel.data_channel = handler
        self.cmd_channel._on_dtp_connection()
        # Can't close right now as the handler would have the socket
        # object disconnected.  This class will be "closed" once the
        # data transfer is completed or the client disconnects.
        #self.close()