Python socket.SocketType() Examples

The following are 30 code examples of socket.SocketType(). 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: common_func.py    From passbytcp with MIT License 6 votes vote down vote up
def _rd_shutdown(self, conn, once=False):
        """action when connection should be read-shutdown
        :type conn: socket.SocketType
        """
        if conn in self.conn_rd:
            self.conn_rd.remove(conn)

        try:
            conn.shutdown(socket.SHUT_RD)
        except:
            pass

        if not once and conn in self.map:  # use the `once` param to avoid infinite loop
            # if a socket is rd_shutdowned, then it's
            #   pair should be wr_shutdown.
            self._wr_shutdown(self.map[conn], True)

        if self.map.get(conn) not in self.conn_rd:
            # if both two connection pair was rd-shutdowned,
            #   this pair sockets are regarded to be completed
            #   so we gonna close them
            self._terminate(conn) 
Example #3
Source File: common_func.py    From passbytcp with MIT License 6 votes vote down vote up
def select_recv(conn, buff_size, timeout=None):
    """add timeout for socket.recv()
    :type conn: socket.SocketType
    :type buff_size: int
    :type timeout: float
    :rtype: Union[bytes, None]
    """
    rlist, _, _ = select.select([conn], [], [], timeout)
    if not rlist:
        # timeout
        raise RuntimeError("recv timeout")

    buff = conn.recv(buff_size)
    if not buff:
        raise RuntimeError("received zero bytes, socket was closed")

    return buff 
Example #4
Source File: common_func.py    From passbytcp with MIT License 6 votes vote down vote up
def select_recv(conn, buff_size, timeout=None):
    """add timeout for socket.recv()
    :type conn: socket.SocketType
    :type buff_size: int
    :type timeout: float
    :rtype: Union[bytes, None]
    """
    rlist, _, _ = select.select([conn], [], [], timeout)
    if not rlist:
        # timeout
        raise RuntimeError("recv timeout")

    buff = conn.recv(buff_size)
    if not buff:
        raise RuntimeError("received zero bytes, socket was closed")

    return buff 
Example #5
Source File: common_func.py    From passbytcp with MIT License 6 votes vote down vote up
def add_conn_pair(self, conn1, conn2, callback=None):
        """
        transfer anything between two sockets

        :type conn1: socket.SocketType
        :type conn2: socket.SocketType
        :param callback: callback in connection finish
        :type callback: Callable
        """
        # mark as readable
        self.conn_rd.add(conn1)
        self.conn_rd.add(conn2)

        # record sockets pairs
        self.map[conn1] = conn2
        self.map[conn2] = conn1

        # record callback
        if callback is not None:
            self.callbacks[conn1] = callback 
Example #6
Source File: common_func.py    From passbytcp with MIT License 6 votes vote down vote up
def _rd_shutdown(self, conn, once=False):
        """action when connection should be read-shutdown
        :type conn: socket.SocketType
        """
        if conn in self.conn_rd:
            self.conn_rd.remove(conn)

        try:
            conn.shutdown(socket.SHUT_RD)
        except:
            pass

        if not once and conn in self.map:  # use the `once` param to avoid infinite loop
            # if a socket is rd_shutdowned, then it's
            #   pair should be wr_shutdown.
            self._wr_shutdown(self.map[conn], True)

        if self.map.get(conn) not in self.conn_rd:
            # if both two connection pair was rd-shutdowned,
            #   this pair sockets are regarded to be completed
            #   so we gonna close them
            self._terminate(conn) 
Example #7
Source File: test_connection.py    From mopidy-mpd with Apache License 2.0 6 votes vote down vote up
def test_init_handles_ipv6_addr(self):
        addr = (
            sentinel.host,
            sentinel.port,
            sentinel.flowinfo,
            sentinel.scopeid,
        )
        protocol = Mock(spec=network.LineProtocol)
        protocol_kwargs = {}
        sock = Mock(spec=socket.SocketType)

        network.Connection.__init__(
            self.mock, protocol, protocol_kwargs, sock, addr, sentinel.timeout
        )
        assert sentinel.host == self.mock.host
        assert sentinel.port == self.mock.port 
Example #8
Source File: test_socket.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_SocketType_is_socketobject(self):
        import _socket
        self.assertTrue(socket.SocketType is _socket.socket)
        s = socket.socket()
        self.assertIsInstance(s, socket.SocketType)
        s.close() 
Example #9
Source File: test_socket.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def testSocketTypeAvailable(self):
        self.assertIs(socket.socket, socket.SocketType) 
Example #10
Source File: test_connection.py    From mopidy-mpd with Apache License 2.0 5 votes vote down vote up
def test_send_callback_respects_io_hup(self):
        self.mock._sock = Mock(spec=socket.SocketType)
        self.mock._sock.send.return_value = 1
        self.mock.send_lock = Mock()
        self.mock.actor_ref = Mock()
        self.mock.send_buffer = b""

        assert network.Connection.send_callback(
            self.mock, sentinel.fd, (GLib.IO_IN | GLib.IO_HUP)
        )
        self.mock.stop.assert_called_once_with(any_unicode) 
Example #11
Source File: test_connection.py    From mopidy-mpd with Apache License 2.0 5 votes vote down vote up
def test_send_callback_respects_io_hup_and_io_err(self):
        self.mock._sock = Mock(spec=socket.SocketType)
        self.mock._sock.send.return_value = 1
        self.mock.send_lock = Mock()
        self.mock.actor_ref = Mock()
        self.mock.send_buffer = b""

        assert network.Connection.send_callback(
            self.mock, sentinel.fd, ((GLib.IO_IN | GLib.IO_HUP) | GLib.IO_ERR)
        )
        self.mock.stop.assert_called_once_with(any_unicode) 
Example #12
Source File: test_connection.py    From mopidy-mpd with Apache License 2.0 5 votes vote down vote up
def test_send_callback_acquires_and_releases_lock(self):
        self.mock.send_lock = Mock()
        self.mock.send_lock.acquire.return_value = True
        self.mock.send_buffer = b""
        self.mock._sock = Mock(spec=socket.SocketType)
        self.mock._sock.send.return_value = 0

        assert network.Connection.send_callback(
            self.mock, sentinel.fd, GLib.IO_IN
        )
        self.mock.send_lock.acquire.assert_called_once_with(False)
        self.mock.send_lock.release.assert_called_once_with() 
Example #13
Source File: test_connection.py    From mopidy-mpd with Apache License 2.0 5 votes vote down vote up
def test_send_callback_fails_to_acquire_lock(self):
        self.mock.send_lock = Mock()
        self.mock.send_lock.acquire.return_value = False
        self.mock.send_buffer = b""
        self.mock._sock = Mock(spec=socket.SocketType)
        self.mock._sock.send.return_value = 0

        assert network.Connection.send_callback(
            self.mock, sentinel.fd, GLib.IO_IN
        )
        self.mock.send_lock.acquire.assert_called_once_with(False)
        assert 0 == self.mock._sock.send.call_count 
Example #14
Source File: test_connection.py    From mopidy-mpd with Apache License 2.0 5 votes vote down vote up
def test_send_recoverable_error(self):
        self.mock._sock = Mock(spec=socket.SocketType)

        for error in (errno.EWOULDBLOCK, errno.EINTR):
            self.mock._sock.send.side_effect = socket.error(error, "")

            network.Connection.send(self.mock, b"data")
            assert 0 == self.mock.stop.call_count 
Example #15
Source File: test_connection.py    From mopidy-mpd with Apache License 2.0 5 votes vote down vote up
def test_send_calls_socket_send_partial_send(self):
        self.mock._sock = Mock(spec=socket.SocketType)
        self.mock._sock.send.return_value = 2

        assert b"ta" == network.Connection.send(self.mock, b"data")
        self.mock._sock.send.assert_called_once_with(b"data") 
Example #16
Source File: test_connection.py    From mopidy-mpd with Apache License 2.0 5 votes vote down vote up
def test_send_unrecoverable_error(self):
        self.mock._sock = Mock(spec=socket.SocketType)
        self.mock._sock.send.side_effect = socket.error

        assert b"" == network.Connection.send(self.mock, b"data")
        self.mock.stop.assert_called_once_with(any_unicode) 
Example #17
Source File: test_socket.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_SocketType_is_socketobject(self):
        import _socket
        self.assertTrue(socket.SocketType is _socket.socket)
        s = socket.socket()
        self.assertIsInstance(s, socket.SocketType)
        s.close() 
Example #18
Source File: common_func.py    From passbytcp with MIT License 5 votes vote down vote up
def _wr_shutdown(self, conn, once=False):
        """action when connection should be write-shutdown
        :type conn: socket.SocketType
        """
        try:
            conn.shutdown(socket.SHUT_WR)
        except:
            pass

        if not once and conn in self.map:  # use the `once` param to avoid infinite loop
            #   pair should be rd_shutdown.
            # if a socket is wr_shutdowned, then it's
            self._rd_shutdown(self.map[conn], True) 
Example #19
Source File: test_socket.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def testSocketTypeAvailable(self):
        self.assertIs(socket.socket, socket.SocketType) 
Example #20
Source File: common_func.py    From passbytcp with MIT License 5 votes vote down vote up
def add_conn_pair(self, conn1, conn2,tmp=None, callback=None):
        """
        transfer anything between two sockets

        :type conn1: socket.SocketType
        :type conn2: socket.SocketType
        :param callback: callback in connection finish
        :type callback: Callable
        """
        # mark as readable
        self.conn_rd.add(conn1)
        self.conn_rd.add(conn2)

        # record sockets pairs
        self.map[conn1] = conn2
        self.map[conn2] = conn1



        # record callback
        if callback is not None:
            self.callbacks[conn1] = callback

        if tmp is not None:
            conn2.send(tmp)
            logging.info("tmp send:{}".format(len(tmp))) 
Example #21
Source File: test_connection.py    From mopidy-mpd with Apache License 2.0 5 votes vote down vote up
def test_recv_callback_recoverable_error(self):
        self.mock._sock = Mock(spec=socket.SocketType)

        for error in (errno.EWOULDBLOCK, errno.EINTR):
            self.mock._sock.recv.side_effect = socket.error(error, "")
            assert network.Connection.recv_callback(
                self.mock, sentinel.fd, GLib.IO_IN
            )
            assert 0 == self.mock.stop.call_count 
Example #22
Source File: common_func.py    From passbytcp with MIT License 5 votes vote down vote up
def _wr_shutdown(self, conn, once=False):
        """action when connection should be write-shutdown
        :type conn: socket.SocketType
        """
        try:
            conn.shutdown(socket.SHUT_WR)
        except:
            pass

        if not once and conn in self.map:  # use the `once` param to avoid infinite loop
            #   pair should be rd_shutdown.
            # if a socket is wr_shutdowned, then it's
            self._rd_shutdown(self.map[conn], True) 
Example #23
Source File: common_func.py    From passbytcp with MIT License 5 votes vote down vote up
def _terminate(self, conn):
        """terminate a sockets pair (two socket)
        :type conn: socket.SocketType
        :param conn: any one of the sockets pair
        """
        try_close(conn)  # close the first socket

        server_pool.ServerPool.bridgeRemove += 1

        # ------ close and clean the mapped socket, if exist ------
        if conn in self.map:
            _mapped_conn = self.map[conn]
            try_close(_mapped_conn)
            if _mapped_conn in self.map:
                del self.map[_mapped_conn]

            del self.map[conn]  # clean the first socket
        else:
            _mapped_conn = None  # just a fallback

        # ------ callback --------
        # because we are not sure which socket are assigned to callback,
        #   so we should try both
        if conn in self.callbacks:
            try:
                self.callbacks[conn]()
            except Exception as e:
                log.error("traceback error: {}".format(e))
                log.debug(traceback.format_exc())
            del self.callbacks[conn]
        elif _mapped_conn and _mapped_conn in self.callbacks:
            try:
                self.callbacks[_mapped_conn]()
            except Exception as e:
                log.error("traceback error: {}".format(e))
                log.debug(traceback.format_exc())
            del self.callbacks[_mapped_conn] 
Example #24
Source File: test_socket.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_SocketType_is_socketobject(self):
        import _socket
        self.assertTrue(socket.SocketType is _socket.socket)
        s = socket.socket()
        self.assertIsInstance(s, socket.SocketType)
        s.close() 
Example #25
Source File: common_func.py    From passbytcp with MIT License 5 votes vote down vote up
def _terminate(self, conn):
        """terminate a sockets pair (two socket)
        :type conn: socket.SocketType
        :param conn: any one of the sockets pair
        """
        try_close(conn)  # close the first socket

        # ------ close and clean the mapped socket, if exist ------
        if conn in self.map:
            _mapped_conn = self.map[conn]
            try_close(_mapped_conn)
            if _mapped_conn in self.map:
                del self.map[_mapped_conn]

            del self.map[conn]  # clean the first socket
        else:
            _mapped_conn = None  # just a fallback

        # ------ callback --------
        # because we are not sure which socket are assigned to callback,
        #   so we should try both
        if conn in self.callbacks:
            try:
                self.callbacks[conn]()
            except Exception as e:
                log.error("traceback error: {}".format(e))
                log.debug(traceback.format_exc())
            del self.callbacks[conn]
        elif _mapped_conn and _mapped_conn in self.callbacks:
            try:
                self.callbacks[_mapped_conn]()
            except Exception as e:
                log.error("traceback error: {}".format(e))
                log.debug(traceback.format_exc())
            del self.callbacks[_mapped_conn] 
Example #26
Source File: test_connection.py    From mopidy-mpd with Apache License 2.0 5 votes vote down vote up
def test_enable_recv_already_registered(self):
        self.mock._sock = Mock(spec=socket.SocketType)
        self.mock.recv_id = sentinel.tag

        network.Connection.enable_recv(self.mock)
        assert 0 == GLib.io_add_watch.call_count 
Example #27
Source File: test_connection.py    From mopidy-mpd with Apache License 2.0 5 votes vote down vote up
def test_init_ensure_nonblocking_io(self):
        sock = Mock(spec=socket.SocketType)

        network.Connection.__init__(
            self.mock,
            Mock(),
            {},
            sock,
            (sentinel.host, sentinel.port),
            sentinel.timeout,
        )
        sock.setblocking.assert_called_once_with(False) 
Example #28
Source File: test_connection.py    From mopidy-mpd with Apache License 2.0 5 votes vote down vote up
def test_init_stores_values_in_attributes(self):
        addr = (sentinel.host, sentinel.port)
        protocol = Mock(spec=network.LineProtocol)
        protocol_kwargs = {}
        sock = Mock(spec=socket.SocketType)

        network.Connection.__init__(
            self.mock, protocol, protocol_kwargs, sock, addr, sentinel.timeout
        )
        assert sock == self.mock._sock
        assert protocol == self.mock.protocol
        assert protocol_kwargs == self.mock.protocol_kwargs
        assert sentinel.timeout == self.mock.timeout
        assert sentinel.host == self.mock.host
        assert sentinel.port == self.mock.port 
Example #29
Source File: test_connection.py    From mopidy-mpd with Apache License 2.0 5 votes vote down vote up
def test_stop_disables_recv_send_and_timeout(self):
        self.mock.stopping = False
        self.mock.actor_ref = Mock()
        self.mock._sock = Mock(spec=socket.SocketType)

        network.Connection.stop(self.mock, sentinel.reason)
        self.mock.disable_timeout.assert_called_once_with()
        self.mock.disable_recv.assert_called_once_with()
        self.mock.disable_send.assert_called_once_with() 
Example #30
Source File: test_connection.py    From mopidy-mpd with Apache License 2.0 5 votes vote down vote up
def test_stop_closes_socket(self):
        self.mock.stopping = False
        self.mock.actor_ref = Mock()
        self.mock._sock = Mock(spec=socket.SocketType)

        network.Connection.stop(self.mock, sentinel.reason)
        self.mock._sock.close.assert_called_once_with()