Python socket.SO_RCVTIMEO Examples

The following are 6 code examples of socket.SO_RCVTIMEO(). 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: networking_utils.py    From eva with Apache License 2.0 6 votes vote down vote up
def set_socket_io_timeouts(transport, seconds, useconds=0):
    """
        Set timeout for transport sockets.
        Useful with highly concurrent workloads.

        Returns False if it failed to set the timeouts.
    """
    seconds = (seconds).to_bytes(8, 'little')
    useconds = (useconds).to_bytes(8, 'little')
    sock = transport.get_extra_info('socket')
    try:
        sock.setsockopt(
            socket.SOL_SOCKET,
            socket.SO_RCVTIMEO,
            seconds + useconds,
        )
        sock.setsockopt(
            socket.SOL_SOCKET,
            socket.SO_SNDTIMEO,
            seconds + useconds,
        )
        return True
    except OSError:
        return False 
Example #2
Source File: socket_port.py    From xArm-Python-SDK with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, server_ip, server_port, rxque_max=XCONF.SocketConf.TCP_RX_QUE_MAX, heartbeat=False,
                 buffer_size=XCONF.SocketConf.TCP_CONTROL_BUF_SIZE):
        super(SocketPort, self).__init__(rxque_max)
        if server_port == XCONF.SocketConf.TCP_CONTROL_PORT:
            self.port_type = 'main-socket'
            # self.com.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, 5)
        else:
            self.port_type = 'report-socket'
        try:
            socket.setdefaulttimeout(1)
            self.com = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.com.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.com.setblocking(True)
            self.com.settimeout(1)
            self.com.connect((server_ip, server_port))
            logger.info('{} connect {} success'.format(self.port_type, server_ip))
            # logger.info('{} connect {}:{} success'.format(self.port_type, server_ip, server_port))

            self._connected = True
            self.buffer_size = buffer_size
            # time.sleep(1)

            self.rx_parse = -1
            self.com_read = self.com.recv
            self.com_write = self.com.send
            self.write_lock = threading.Lock()
            self.start()
            if heartbeat:
                self.heartbeat_thread = HeartBeatThread(self)
                self.heartbeat_thread.start()
        except Exception as e:
            logger.info('{} connect {} failed, {}'.format(self.port_type, server_ip, e))
            # logger.error('{} connect {}:{} failed, {}'.format(self.port_type, server_ip, server_port, e))
            self._connected = False 
Example #3
Source File: base_socket_connection.py    From boofuzz with GNU General Public License v2.0 5 votes vote down vote up
def open(self):
        """
        Opens connection to the target. Make sure to call close!

        Returns:
            None
        """
        self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, _seconds_to_sockopt_format(self._send_timeout))
        self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, _seconds_to_sockopt_format(self._recv_timeout)) 
Example #4
Source File: socket.py    From PySocket with Apache License 2.0 4 votes vote down vote up
def new_accept(orgin_method, self, *args, **kwds):

    while True:
        return_value = orgin_method(*args, **kwds)
        self_socket = return_value[0]
        client_ip, client_port = return_value[1][:2]
        server_addrs = self._server_addrs
        client_list = self._all_client_list.get(server_addrs, {})
        if len(client_list) < self._limit_clients_num or client_ip in client_list:
            self_socket._server_addrs = self._server_addrs
            self_socket.close = self_socket.new_close
            logging.debug("[socket] add client %s:%d" %(client_ip, client_port))
            if client_list.get(client_ip, None) == None:
                client_list.update({client_ip : {"client_num":0, "last_up_time":0}})
            client_list[client_ip]["client_num"] += 1
            self._all_client_list[server_addrs].update(client_list)
            if set_close_timeout:
                # set recv_timeout and send_timeout , struct.pack("II", some_num_secs, some_num_microsecs)
                self_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, struct.pack("LL", recv_timeout, 0))
                self_socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, struct.pack("LL", send_timeout, 0))
            return return_value
        else:
            for k,v in self._all_client_list[server_addrs].copy().items():
                last_up_time = v["last_up_time"]
                if time.time() - last_up_time > recvfrom_timeout and v["client_num"] < 1:
                    if set_close_timeout:
                        self_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, struct.pack("LL", recv_timeout, 0))
                        self_socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, struct.pack("LL", send_timeout, 0))
                    logging.info("[socket] remove the client %s" % (k))
                    del client_list[k]
                    if client_list.get(client_ip, None) == None:
                        client_list.update({client_ip : {"client_num":0, "last_up_time":0}})
                    client_list[client_ip]["client_num"] += 1
                    self._all_client_list[server_addrs].update(client_list)
                    self_socket._server_addrs = self._server_addrs
                    self_socket.close = self_socket.new_close
                    return return_value
        if time.time() - self.last_log_time[0] > 10:
            logging.error("[socket] the server_addrs %s client more than %d" % (server_addrs, self._limit_clients_num))
            self.last_log_time[0] = time.time()
        self_socket.close()


# 处理Udp连接 
Example #5
Source File: socket_connection.py    From fuzzowski with GNU General Public License v2.0 4 votes vote down vote up
def open(self):
        """
        Opens connection to the target. Make sure to call close!

        Returns:
            None
        """
        # Create socket
        if self.proto == "tcp" or self.proto == "ssl":
            self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        elif self.proto == "udp":
            self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            if self.bind:
                self._sock.bind(('0.0.0.0', self.bind))
            if self._udp_broadcast:
                self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True)
        elif self.proto == "raw-l2":
            self._sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
        elif self.proto == "raw-l3":
            self._sock = socket.socket(socket.AF_PACKET, socket.SOCK_DGRAM)
        else:
            raise exception.FuzzowskiRuntimeError("INVALID PROTOCOL SPECIFIED: %s" % self.proto)

        self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, _seconds_to_second_microsecond_struct(self._send_timeout))
        self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, _seconds_to_second_microsecond_struct(self._recv_timeout))

        # Connect is needed only for TCP protocols
        if self.proto == "tcp" or self.proto == "ssl":
            try:
                self._sock.settimeout(self._recv_timeout)
                self._sock.connect((self.host, self.port))
            except (socket.timeout, TimeoutError) as e:
                raise exception.FuzzowskiTargetConnectionFailedError('ETIMEDOUT')
            except OSError as e:  # socket.error
                if e.errno == errno.ECONNREFUSED:
                    # raise exception.FuzzowskiTargetConnectionFailedError(e.message)
                    raise exception.FuzzowskiTargetConnectionFailedError('ECONNREFUSED')
                elif e.errno == errno.EALREADY:
                    raise exception.FuzzowskiTargetConnectionFailedError('EALREADY')
                elif e.errno == errno.EINPROGRESS:
                    raise exception.FuzzowskiTargetConnectionFailedError('EINPROGRESS')
                else:  # ??
                    raise exception.FuzzowskiTargetConnectionFailedError(errno.errorcode.get(e.errno))

        # if SSL is requested, then enable it.
        if self.proto == "ssl":
            ssl_sock = ssl.wrap_socket(self._sock)
            # TODO: Python3 change, maybe should use a context instead of deprecated ssl.wrap_socket?
            self._sock = ssl_sock
            # self._sock = httplib.FakeSocket(self._sock, ssl_sock) 
Example #6
Source File: socket_connection.py    From fuzzowski with GNU General Public License v2.0 4 votes vote down vote up
def recv(self, max_bytes):
        """
        Receive up to max_bytes data from the target.

        Args:
            max_bytes (int): Maximum number of bytes to receive.

        Returns:
            Received data.
        """
        try:
            if self.proto in ['tcp', 'ssl']:
                data = self._sock.recv(max_bytes)
            elif self.proto == 'udp':
                # Not necessary to bind to a port to use this, right?
                # if self.bind:
                data, _ = self._sock.recvfrom(max_bytes)
                # else:
                #     raise exception.FuzzowskiRuntimeError(
                #         "SocketConnection.recv() for UDP requires a bind address/port."
                #         " Current value: {}".format(self.bind))
            elif self.proto in ['raw-l2', 'raw-l3']:
                # receive on raw is not supported. Since there is no specific protocol for raw, we would just have to
                # dump everything off the interface anyway, which is probably not what the user wants.
                data = b''
            else:
                raise exception.FuzzowskiRuntimeError("INVALID PROTOCOL SPECIFIED: %s" % self.proto)
        except socket.timeout:
            data = b''
            # raise exception.FuzzowskiTargetRecvTimeout()
        except socket.error as e:
            if e.errno == errno.ECONNABORTED:
                # raise(exception.FuzzowskiTargetConnectionAborted(socket_errno=e.errno, socket_errmsg=e.strerror), None, sys.exc_info()[2])
                raise exception.FuzzowskiTargetConnectionAborted(socket_errno=e.errno, socket_errmsg=e.strerror)  # .with_traceback(sys.exc_info()[2])
            elif (e.errno == errno.ECONNRESET) or \
                    (e.errno == errno.ENETRESET) or \
                    (e.errno == errno.ETIMEDOUT):
                # raise(exception.FuzzowskiTargetConnectionReset, None, sys.exc_info()[2])
                raise exception.FuzzowskiTargetConnectionReset  # .with_traceback(sys.exc_info()[2])
            elif e.errno == errno.EWOULDBLOCK or e.errno == errno.EAGAIN:  # timeout condition if using SO_RCVTIMEO or SO_SNDTIMEO
                # raise exception.FuzzowskiTargetRecvTimeout()
                data = b''
            else:
                raise

        return data