Python socket.fileno() Examples

The following are 21 code examples of socket.fileno(). 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: main.py    From uPyEcho with Apache License 2.0 7 votes vote down vote up
def poll(self, timeout=100):
        if self.use_poll:
            ready = self.poller.poll(timeout)
        else:
            ready = []
            if len(self.targets) > 0:
                (rlist, wlist, xlist) = select.select(
                    self.targets.keys(), [], [], timeout
                )
                ready = [(x, None) for x in rlist]

        for one_ready in ready:
            target = self.targets.get(one_ready[0].fileno(), None)
            dbg("Targets %s" % str(self.targets.keys()))
            if target:
                # dbg("get socket with fileno: %s" % str(one_ready[0].fileno()) +  " len: %s" % len(one_ready) + " selected: %s " % str(target.fileno()) )
                # update time
                target.do_read(one_ready[0]) 
Example #2
Source File: test_select.py    From CTFCrackTools with GNU General Public License v3.0 6 votes vote down vote up
def testBadSelectableTypes(self):
        class Nope: pass

        class Almost1:
            def fileno(self):
                return 'fileno'

        class Almost2:
            def fileno(self):
                return 'fileno'

        # Test some known error conditions
        for bad_selectable in [None, 1, object(), Nope(), Almost1(), Almost2()]:
            try:
                timeout = 0 # Can't wait forever
                rfd, wfd, xfd = select.select([bad_selectable], [], [], timeout)
            except (TypeError, select.error), x:
                pass
            else:
                self.fail("Selecting on '%s' should have raised TypeError or select.error" % str(bad_selectable)) 
Example #3
Source File: main.py    From uPyEcho with Apache License 2.0 6 votes vote down vote up
def do_read(self, socket):
        fileno = socket.fileno()
        dbg("Fileno %s" % fileno + " socket fileno %s" % self.socket.fileno())

        if fileno == self.socket.fileno():
            try:
                (client_socket, client_address) = self.socket.accept()
                self.poller.add(self, client_socket)
                self.client_sockets[client_socket.fileno()] = client_socket
            except Exception as e:
                dbg("################################## Socket busy! %s" % str(e))
        else:
            data, sender = self.client_sockets[fileno].recvfrom(4096)
            if not data:
                self.poller.remove(self, self.client_sockets[fileno])
                self.client_sockets[fileno].close()

            else:
                dbg("send response to socket!: %s" % str(fileno))
                self.handle_request(data, sender, self.client_sockets[fileno])
            gc.collect() 
Example #4
Source File: main.py    From uPyEcho with Apache License 2.0 6 votes vote down vote up
def do_read(self, fileno):
        data, sender = self.recvfrom(1024)
        if data:
            # Issue https://github.com/kakopappa/arduino-esp8266-alexa-multiple-wemo-switch/issues/22
            if data.find(b"M-SEARCH") == 0 and self.inprogress is False:
                if (
                    data.find(b"upnp:rootdevice") != -1
                    or data.find(b"ssdp:all") != -1
                    or data.find(b"urn:Belkin:device:**") != -1
                ):
                    for device in self.devices:
                        time.sleep(0.5)
                        device.respond_to_search(
                            sender, "urn:Belkin:device:**"
                        )  # (sender, 'upnp:rootdevice')?
                        self.inprogress = True
                else:
                    pass
            else:
                pass

    # Receive network data 
Example #5
Source File: test_select.py    From CTFCrackTools-V2 with GNU General Public License v3.0 6 votes vote down vote up
def testBadSelectableTypes(self):
        class Nope: pass

        class Almost1:
            def fileno(self):
                return 'fileno'

        class Almost2:
            def fileno(self):
                return 'fileno'

        # Test some known error conditions
        for bad_selectable in [None, 1, object(), Nope(), Almost1(), Almost2()]:
            try:
                timeout = 0 # Can't wait forever
                rfd, wfd, xfd = select.select([bad_selectable], [], [], timeout)
            except (TypeError, select.error), x:
                pass
            else:
                self.fail("Selecting on '%s' should have raised TypeError or select.error" % str(bad_selectable)) 
Example #6
Source File: test_select.py    From medicare-demo with Apache License 2.0 6 votes vote down vote up
def testBadSelectableTypes(self):
        class Nope: pass

        class Almost1:
            def fileno(self):
                return 'fileno'

        class Almost2:
            def fileno(self):
                return 'fileno'

        # Test some known error conditions
        for bad_selectable in [None, 1, object(), Nope(), Almost1(), Almost2()]:
            try:
                timeout = 0 # Can't wait forever
                rfd, wfd, xfd = select.select([bad_selectable], [], [], timeout)
            except (TypeError, select.error), x:
                pass
            else:
                self.fail("Selecting on '%s' should have raised TypeError or select.error" % str(bad_selectable)) 
Example #7
Source File: tcp_connection.py    From PySyncObj with MIT License 6 votes vote down vote up
def connect(self, host, port):
        self.__state = CONNECTION_STATE.DISCONNECTED
        self.__fileno = None
        self.__socket = socket.socket(_getAddrType(host), socket.SOCK_STREAM)
        self.__socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self.__sendBufferSize)
        self.__socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.__recvBufferSize)
        self.__socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        self.__socket.setblocking(0)
        self.__readBuffer = bytes()
        self.__writeBuffer = bytes()
        self.__lastReadTime = monotonicTime()

        try:
            self.__socket.connect((host, port))
        except socket.error as e:
            if e.errno not in (socket.errno.EINPROGRESS, socket.errno.EWOULDBLOCK):
                return False
        self.__fileno = self.__socket.fileno()
        self.__state = CONNECTION_STATE.CONNECTING
        self.__poller.subscribe(self.__fileno,
                                 self.__processConnection,
                                 POLL_EVENT_TYPE.READ | POLL_EVENT_TYPE.WRITE | POLL_EVENT_TYPE.ERROR)
        return True 
Example #8
Source File: test_select.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def _testSelectOnSocketFileno(self):
        self.cli.setblocking(0)
        self.cli.connect( (self.HOST, self.PORT) )
        return
        try:
            rfd, wfd, xfd = select.select([self.cli.fileno()], [], [], 1)
        except Exception, x:
            self.fail("Selecting on socket.fileno() should not have raised exception: %s" % str(x)) 
Example #9
Source File: main.py    From uPyEcho with Apache License 2.0 5 votes vote down vote up
def add(self, target, socket=None):
        if not socket:
            socket = target.sockets()
        if self.use_poll:
            self.poller.register(socket, select.POLLIN)
        # dbg("add device on fileno: %s" % socket.fileno() )
        self.targets[socket.fileno()] = target
        # dbg("size targets: %s" % len(self.targets)) 
Example #10
Source File: test_select.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def _testSelectOnSocketFileno(self):
        self.cli.setblocking(0)
        self.cli.connect( (self.HOST, self.PORT) )
        return
        try:
            rfd, wfd, xfd = select.select([self.cli.fileno()], [], [], 1)
        except Exception, x:
            self.fail("Selecting on socket.fileno() should not have raised exception: %s" % str(x)) 
Example #11
Source File: test_select.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def _testSelectOnSocketFileno(self):
        self.cli.setblocking(0)
        self.cli.connect( (self.HOST, self.PORT) )
        return
        try:
            rfd, wfd, xfd = select.select([self.cli.fileno()], [], [], 1)
        except Exception, x:
            self.fail("Selecting on socket.fileno() should not have raised exception: %s" % str(x)) 
Example #12
Source File: posix.py    From pymux with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _read_chunk_from_socket(socket):
    """
    (coroutine)
    Turn socket reading into coroutine.
    """
    fd = socket.fileno()
    f = Future()

    def read_callback():
        get_event_loop().remove_reader(fd)

        # Read next chunk.
        try:
            data = socket.recv(1024)
        except OSError as e:
            # On OSX, when we try to create a new window by typing "pymux
            # new-window" in a centain pane, very often we get the following
            # error: "OSError: [Errno 9] Bad file descriptor."
            # This doesn't seem very harmful, and we can just try again.
            logger.warning('Got OSError while reading data from client: %s. '
                           'Trying again.', e)
            f.set_result('')
            return

        if data:
            f.set_result(data)
        else:
            f.set_exception(BrokenPipeError)

    get_event_loop().add_reader(fd, read_callback)

    return f 
Example #13
Source File: posix.py    From pymux with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, socket):
        self.socket = socket
        self._fd = socket.fileno()
        self._recv_buffer = b'' 
Example #14
Source File: posix.py    From pymux with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bind_and_listen_on_posix_socket(socket_name, accept_callback):
    """
    :param accept_callback: Called with `PosixSocketConnection` when a new
        connection is established.
    """
    assert socket_name is None or isinstance(socket_name, six.text_type)
    assert callable(accept_callback)

    # Py2 uses 0027 and Py3 uses 0o027, but both know
    # how to create the right value from the string '0027'.
    old_umask = os.umask(int('0027', 8))

    # Bind socket.
    socket_name, socket = _bind_posix_socket(socket_name)

    _ = os.umask(old_umask)

    # Listen on socket.
    socket.listen(0)

    def _accept_cb():
        connection, client_address = socket.accept()
        # Note: We don't have to put this socket in non blocking mode.
        #       This can cause crashes when sending big packets on OS X.

        posix_connection = PosixSocketConnection(connection)

        accept_callback(posix_connection)

    get_event_loop().add_reader(socket.fileno(), _accept_cb)

    logger.info('Listening on %r.' % socket_name)
    return socket_name 
Example #15
Source File: tcp_connection.py    From PySyncObj with MIT License 5 votes vote down vote up
def fileno(self):
        return self.__fileno 
Example #16
Source File: tcp_connection.py    From PySyncObj with MIT License 5 votes vote down vote up
def __init__(self, poller, onMessageReceived = None, onConnected = None, onDisconnected = None,
                 socket=None, timeout=10.0, sendBufferSize = 2 ** 13, recvBufferSize = 2 ** 13):

        self.sendRandKey = None
        self.recvRandKey = None
        self.encryptor = None

        self.__socket = socket
        self.__readBuffer = bytes()
        self.__writeBuffer = bytes()
        self.__lastReadTime = monotonicTime()
        self.__timeout = timeout
        self.__poller = poller
        if socket is not None:
            self.__socket = socket
            self.__fileno = socket.fileno()
            self.__state = CONNECTION_STATE.CONNECTED
            self.__poller.subscribe(self.__fileno,
                                     self.__processConnection,
                                     POLL_EVENT_TYPE.READ | POLL_EVENT_TYPE.WRITE | POLL_EVENT_TYPE.ERROR)
        else:
            self.__state = CONNECTION_STATE.DISCONNECTED
            self.__fileno = None
            self.__socket = None

        self.__onMessageReceived = onMessageReceived
        self.__onConnected = onConnected
        self.__onDisconnected = onDisconnected
        self.__sendBufferSize = sendBufferSize
        self.__recvBufferSize = recvBufferSize 
Example #17
Source File: dns.py    From uPyPortal with Apache License 2.0 5 votes vote down vote up
def poll(self, ip, timeout = 100):
        ready = self.poller.poll(timeout)
        for one_ready in ready:
            target = self.targets.get(one_ready[0].fileno(), None)
            if target:
                try:
                    data, sender = target.recvfrom(1024)
                    p = DNSQuery(data)
                    if any(word in p.domain for word in config.DNS_ANSWERS):
                        target.sendto(p.answer(ip), sender)
                        dbg('Replying: {:s} -> {:s}'.format(p.domain, ip))
                    #else:
                    #    dbg('Avoid responding: {:s} -> {:s}'.format(p.domain, ip))
                except Exception as e:
                    dbg('Exception occurs: ' + str(e)) 
Example #18
Source File: dns.py    From uPyPortal with Apache License 2.0 5 votes vote down vote up
def remove(self, socket = None):
        if not socket:
            return
        self.poller.unregister(socket)
        del(self.targets[socket.fileno()]) 
Example #19
Source File: dns.py    From uPyPortal with Apache License 2.0 5 votes vote down vote up
def add(self, socket = None):
        if not socket:
            return
        self.poller.register(socket, select.POLLIN)
        self.targets[socket.fileno()] = socket 
Example #20
Source File: main.py    From uPyEcho with Apache License 2.0 5 votes vote down vote up
def fileno(self):
        return self.socket.fileno() 
Example #21
Source File: main.py    From uPyEcho with Apache License 2.0 5 votes vote down vote up
def remove(self, target, socket=None):
        if not socket:
            socket = target.sockets()
        if self.use_poll:
            self.poller.unregister(socket)
        # dbg("remove device on fileno: %s" % socket.fileno() )
        gc.collect()