Python socket.SO_SNDBUF Examples

The following are 30 code examples of socket.SO_SNDBUF(). 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: virtualrouter_plugin.py    From zstack-utility with Apache License 2.0 6 votes vote down vote up
def set_bootstrap_info(self, req):
        cmd = jsonobject.loads(req[http.REQUEST_BODY])
        info = jsonobject.dumps(cmd.info, True)
        socket_path = cmd.socketPath
        
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1)
        buf_size = s.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
        info_len = len(info)
        if info_len < buf_size:
            # as there is no fflush() in python, we have to create a message
            # matching to the socket buffer to force it to send the message immediately
            padding_len = buf_size - info_len
            padding = ' ' * padding_len
            info = '%s%s' % (info, padding)

        try:
            logger.debug('send appliance vm bootstrap info to %s\n%s' % (socket_path, info))
            s.connect(socket_path)
            s.sendall(info)
        finally:
            s.close()
        
        rsp = PrepareBootstrapInfoRsp()
        return jsonobject.dumps(rsp) 
Example #2
Source File: comms.py    From kivy-smoothie-host with GNU General Public License v3.0 6 votes vote down vote up
def connection_made(self, transport):
        self.transport = transport
        self.log.debug('SerialConnection: port opened: {}'.format(transport))
        if self.is_net:
            # we don't want to buffer the entire file on the host
            transport.get_extra_info('socket').setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
            self.log.info("SerialConnection: Setting net tx buf to 2048")
            # for net we want to limit how much we queue up otherwise the whole file gets queued
            # this also gives us more progress more often
            transport.set_write_buffer_limits(high=1024, low=256)
            self.log.info('SerialConnection: Buffer limits: {} - {}'.format(transport._high_water, transport._low_water))
        else:
            transport.set_write_buffer_limits(high=1024, low=64)
            self.log.info('SerialConnection: Buffer limits: {} - {}'.format(transport._high_water, transport._low_water))
            # transport.serial.rts = False  # You can manipulate Serial object via transport
            transport.serial.reset_input_buffer()
            transport.serial.reset_output_buffer()
            # transport.serial.set_low_latency_mode(True)
            # print(transport.serial) 
Example #3
Source File: tcp_server.py    From PySyncObj with MIT License 6 votes vote down vote up
def __onNewConnection(self, descr, event):
        if event & POLL_EVENT_TYPE.READ:
            try:
                sock, addr = self.__socket.accept()
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self.__sendBufferSize)
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.__recvBufferSize)
                sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
                sock.setblocking(0)
                conn = TcpConnection(poller=self.__poller,
                                     socket=sock,
                                     timeout=self.__connectionTimeout,
                                     sendBufferSize=self.__sendBufferSize,
                                     recvBufferSize=self.__recvBufferSize)
                self.__onNewConnectionCallback(conn)
            except socket.error as e:
                if e.errno not in (socket.errno.EAGAIN, socket.errno.EWOULDBLOCK):
                    self.unbind()
                    return

        if event & POLL_EVENT_TYPE.ERROR:
            self.unbind()
            return 
Example #4
Source File: 1_8_modify_buff_size.py    From Python-Network-Programming-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
def modify_buff_size():
    sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
    
    # Get the size of the socket's send buffer
    bufsize = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
    print ("Buffer size [Before]:%d" %bufsize)
    
    sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
    sock.setsockopt(
            socket.SOL_SOCKET,
            socket.SO_SNDBUF,
            SEND_BUF_SIZE)
    sock.setsockopt(
            socket.SOL_SOCKET,
            socket.SO_RCVBUF,
            RECV_BUF_SIZE)
    bufsize = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
    print ("Buffer size [After]:%d" %bufsize) 
Example #5
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 #6
Source File: parent.py    From mitogen with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_socketpair(size=None):
    """
    Create a :func:`socket.socketpair` for use as a child's UNIX stdio
    channels. As socketpairs are bidirectional, they are economical on file
    descriptor usage as one descriptor can be used for ``stdin`` and
    ``stdout``. As they are sockets their buffers are tunable, allowing large
    buffers to improve file transfer throughput and reduce IO loop iterations.
    """
    if size is None:
        size = mitogen.core.CHUNK_SIZE

    parentfp, childfp = socket.socketpair()
    for fp in parentfp, childfp:
        fp.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, size)

    return parentfp, childfp 
Example #7
Source File: 11_8_modify_buff_size.py    From Python-Network-Programming with MIT License 6 votes vote down vote up
def modify_buff_size():
    sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
    
    # Get the size of the socket's send buffer
    bufsize = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
    print ("Buffer size [Before]:%d" %bufsize)
    
    sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
    sock.setsockopt(
            socket.SOL_SOCKET,
            socket.SO_SNDBUF,
            SEND_BUF_SIZE)
    sock.setsockopt(
            socket.SOL_SOCKET,
            socket.SO_RCVBUF,
            RECV_BUF_SIZE)
    bufsize = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
    print ("Buffer size [After]:%d" %bufsize) 
Example #8
Source File: test_socket.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def testSO_SNDBUF(self):
        self.test_udp        = 1
        self.test_tcp_client = 1
        self.test_tcp_server = 1
        self._testOption(socket.SOL_SOCKET, socket.SO_SNDBUF, [1024, 4096, 16384])
        self._testInheritedOption(socket.SOL_SOCKET, socket.SO_SNDBUF, [1024, 4096, 16384]) 
Example #9
Source File: linux.py    From isip with MIT License 5 votes vote down vote up
def __init__(self, iface = None, type = ETH_P_ALL, filter=None, nofilter=0):
        if iface is None:
            iface = conf.iface
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0)
        _flush_fd(self.ins)
        if not nofilter: 
            if conf.except_filter:
                if filter:
                    filter = "(%s) and not (%s)" % (filter, conf.except_filter)
                else:
                    filter = "not (%s)" % conf.except_filter
            if filter is not None:
                attach_filter(self.ins, filter)
        self.ins.bind((iface, type))
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
        self.outs = self.ins
        self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30)
        sa_ll = self.outs.getsockname()
        if sa_ll[3] in conf.l2types:
            self.LL = conf.l2types[sa_ll[3]]
        elif sa_ll[1] in conf.l3types:
            self.LL = conf.l3types[sa_ll[1]]
        else:
            self.LL = conf.default_l2
            warning("Unable to guess type (interface=%s protocol=%#x family=%i). Using %s" % (sa_ll[0],sa_ll[1],sa_ll[3],self.LL.name)) 
Example #10
Source File: socket_.py    From libnl with GNU Lesser General Public License v2.1 5 votes vote down vote up
def nl_socket_set_buffer_size(sk, rxbuf, txbuf):
    """Set socket buffer size of Netlink socket.

    https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L675

    Sets the socket buffer size of a Netlink socket to the specified values `rxbuf` and `txbuf`. Providing a value of 0
    assumes a good default value.

    Positional arguments:
    sk -- Netlink socket (nl_sock class instance).
    rxbuf -- new receive socket buffer size in bytes (integer).
    txbuf -- new transmit socket buffer size in bytes (integer).

    Returns:
    0 on success or a negative error code.
    """
    rxbuf = 32768 if rxbuf <= 0 else rxbuf
    txbuf = 32768 if txbuf <= 0 else txbuf
    if sk.s_fd == -1:
        return -NLE_BAD_SOCK

    try:
        sk.socket_instance.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, txbuf)
    except OSError as exc:
        return -nl_syserr2nlerr(exc.errno)

    try:
        sk.socket_instance.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, rxbuf)
    except OSError as exc:
        return -nl_syserr2nlerr(exc.errno)

    sk.s_flags |= NL_SOCK_BUFSIZE_SET
    return 0 
Example #11
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 testSocketBufferSize(self):
        bufsize = 16384
        with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, bufsize)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, bufsize) 
Example #12
Source File: test_socket.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def _testTCPClientOption(self, level, option, values):
        sock = None
        try:
            # First listen on a server socket, so that the connection won't be refused.
            server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_sock.bind( (HOST, PORT) )
            server_sock.listen(50)
            # Now do the tests
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self._testSetAndGetOption(sock, level, option, values)
            # now connect the socket i.e. cause the implementation socket to be created
            # First bind, so that the SO_REUSEADDR setting propagates
            sock.bind( (HOST, PORT+1) )
            sock.connect( (HOST, PORT) )
            msg = "Option value '%s'='%s' did not propagate to implementation socket" % (option, values[-1])
            if option in (socket.SO_RCVBUF, socket.SO_SNDBUF):
                # NOTE: there's no guarantee that bufsize will be the
                # exact setsockopt value, particularly after
                # establishing a connection. seems it will be *at least*
                # the values we test (which are rather small) on
                # BSDs.
                self.assert_(sock.getsockopt(level, option) >= values[-1], msg)
            else:
                self.failUnlessEqual(sock.getsockopt(level, option), values[-1], msg)
            self._testSetAndGetOption(sock, level, option, values)
        finally:
            server_sock.close()
            if sock:
                sock.close() 
Example #13
Source File: test_socket.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def testSO_SNDBUF(self):
        self.test_udp = 1
        self.test_tcp_client = 1
        self._testOption(socket.SOL_SOCKET, socket.SO_SNDBUF, [1024, 4096, 16384]) 
Example #14
Source File: linux.py    From POC-EXP with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, type = ETH_P_ALL, filter=None, promisc=None, iface=None, nofilter=0):
        self.type = type
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0)
        _flush_fd(self.ins)
        if iface:
            self.ins.bind((iface, type))
        if not nofilter:
            if conf.except_filter:
                if filter:
                    filter = "(%s) and not (%s)" % (filter, conf.except_filter)
                else:
                    filter = "not (%s)" % conf.except_filter
            if filter is not None:
                attach_filter(self.ins, filter)
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
        self.outs = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30)
        if promisc is None:
            promisc = conf.promisc
        self.promisc = promisc
        if self.promisc:
            if iface is None:
                self.iff = get_if_list()
            else:
                if iface.__class__ is list:
                    self.iff = iface
                else:
                    self.iff = [iface]
            for i in self.iff:
                set_promisc(self.ins, i) 
Example #15
Source File: linux.py    From POC-EXP with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, iface = None, type = ETH_P_ALL, filter=None, nofilter=0):
        if iface is None:
            iface = conf.iface
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0)
        _flush_fd(self.ins)
        if not nofilter: 
            if conf.except_filter:
                if filter:
                    filter = "(%s) and not (%s)" % (filter, conf.except_filter)
                else:
                    filter = "not (%s)" % conf.except_filter
            if filter is not None:
                attach_filter(self.ins, filter)
        self.ins.bind((iface, type))
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
        self.outs = self.ins
        self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30)
        sa_ll = self.outs.getsockname()
        if sa_ll[3] in conf.l2types:
            self.LL = conf.l2types[sa_ll[3]]
        elif sa_ll[1] in conf.l3types:
            self.LL = conf.l3types[sa_ll[1]]
        else:
            self.LL = conf.default_l2
            warning("Unable to guess type (interface=%s protocol=%#x family=%i). Using %s" % (sa_ll[0],sa_ll[1],sa_ll[3],self.LL.name)) 
Example #16
Source File: server.py    From snmpfwd with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, localEndpoint, secret, dataCbFun, ctlCbFun, ctlCbCtx):
        localAf, self.__localEndpoint = localEndpoint[0], localEndpoint[1:]
        self.__secret = secret
        self.__dataCbFun = dataCbFun
        self.__ctlCbFun = ctlCbFun
        self.__ctlCbCtx = ctlCbCtx

        asyncore.dispatcher.__init__(self)

        try: 
            self.create_socket(localAf, socket.SOCK_STREAM)
            self.socket.setsockopt(
                socket.SOL_SOCKET, socket.SO_SNDBUF, 65535
            )
            self.socket.setsockopt(
                socket.SOL_SOCKET, socket.SO_RCVBUF, 65535
            )
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.bind(self.__localEndpoint)
            self.listen(10)

        except socket.error:
            raise error.SnmpfwdError('%s socket error: %s' % (self, sys.exc_info()[1]))

        log.info('%s: listening...' % self) 
Example #17
Source File: server.py    From snmpfwd with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, sock, localEndpoint, remoteEndpoint, secret,
                 dataCbFun, ctlCbFun, ctlCbCtx):
        self.__localEndpoint = localEndpoint
        self.__remoteEndpoint = remoteEndpoint
        self.__secret = secret
        self.__dataCbFun = dataCbFun
        self.__ctlCbFun = ctlCbFun
        self.__ctlCbCtx = ctlCbCtx
        self.__pendingReqs = {}
        self.__pendingCounter = 0
        self.__input = null
        self.socket = None  # asyncore strangeness
        asyncore.dispatcher_with_send.__init__(self, sock)

        try: 
            self.socket.setsockopt(
                socket.SOL_SOCKET, socket.SO_SNDBUF, 65535
            )
            self.socket.setsockopt(
                socket.SOL_SOCKET, socket.SO_RCVBUF, 65535
            )
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        except socket.error:
            raise error.SnmpfwdError('%s socket error: %s' % (self, sys.exc_info()[1]))
        else:
            log.info('%s: serving new connection...' % (self,)) 
Example #18
Source File: client.py    From snmpfwd with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, localEndpoint, remoteEndpoint, secret, dataCbFun):
        localAf, self.__localEndpoint = localEndpoint[0], localEndpoint[1:]
        remoteAf, self.__remoteEndpoint = remoteEndpoint[0], remoteEndpoint[1:]
        self.__secret = secret
        self.__dataCbFun = dataCbFun
        self.__pendingReqs = {}
        self.__pendingCounter = 0
        self.__input = null
        self.__announcementData = null

        if localAf != remoteAf:
            raise error.SnmpfwdError('%s: mismatching address family')

        asyncore.dispatcher_with_send.__init__(self)

        try:
            self.create_socket(localAf, socket.SOCK_STREAM)
            self.socket.setsockopt(
                socket.SOL_SOCKET, socket.SO_SNDBUF, 65535
            )
            self.socket.setsockopt(
                socket.SOL_SOCKET, socket.SO_RCVBUF, 65535
            )
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            self.bind(self.__localEndpoint)
            self.connect(self.__remoteEndpoint)

        except socket.error:
            raise error.SnmpfwdError('%s socket error: %s' % (self, sys.exc_info()[1]))

        log.info('%s: initiated trunk client connection from %s to %s...' % (self, localEndpoint, remoteEndpoint)) 
Example #19
Source File: linux.py    From arissploit with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, type = ETH_P_ALL, filter=None, promisc=None, iface=None, nofilter=0):
        self.type = type
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0)
        if iface:
            self.ins.bind((iface, type))
        if not nofilter:
            if conf.except_filter:
                if filter:
                    filter = "(%s) and not (%s)" % (filter, conf.except_filter)
                else:
                    filter = "not (%s)" % conf.except_filter
            if filter is not None:
                attach_filter(self.ins, filter)
        _flush_fd(self.ins)
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
        self.outs = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30)
        if promisc is None:
            promisc = conf.promisc
        self.promisc = promisc
        if self.promisc:
            if iface is None:
                self.iff = get_if_list()
            else:
                if iface.__class__ is list:
                    self.iff = iface
                else:
                    self.iff = [iface]
            for i in self.iff:
                set_promisc(self.ins, i) 
Example #20
Source File: test_socket.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def _testTCPClientOption(self, level, option, values):
        sock = None
        try:
            # First listen on a server socket, so that the connection won't be refused.
            server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            server_sock.bind( (HOST, PORT) )
            server_sock.listen(50)
            # Now do the tests
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self._testSetAndGetOption(sock, level, option, values)
            # now connect the socket i.e. cause the implementation socket to be created
            # First bind, so that the SO_REUSEADDR setting propagates
            #sock.bind( (HOST, PORT+1) )
            sock.connect( (HOST, PORT) )
            retrieved_option_value = sock.getsockopt(level, option)
            msg = "TCP client option value '%s'='%s' did not propagate to implementation socket: got %s" % (option, values[-1], retrieved_option_value)
            if option in (socket.SO_RCVBUF, socket.SO_SNDBUF):
                # NOTE: there's no guarantee that bufsize will be the
                # exact setsockopt value, particularly after
                # establishing a connection. seems it will be *at least*
                # the values we test (which are rather small) on
                # BSDs.
                self.assert_(retrieved_option_value >= values[-1], msg)
            else:
                self.failUnlessEqual(retrieved_option_value, values[-1], msg)
            self._testSetAndGetOption(sock, level, option, values)
        finally:
            server_sock.close()
            if sock:
                sock.close()
            pass 
Example #21
Source File: mqtt_wrapper.py    From gateway with Apache License 2.0 5 votes vote down vote up
def _get_socket(self):
        sock = self._client.socket()
        if sock is not None:
            return sock

        self.logger.error("MQTT, unexpected disconnection")

        if not self.connected:
            self.logger.error("Impossible to connect - authentication failure ?")
            return None

        # Socket is not opened anymore, try to reconnect for timeout if set
        loop_forever = self.timeout == 0
        delay = 0

        # Loop forever or until timeout is over
        while loop_forever or (delay <= self.timeout):
            try:
                ret = self._client.reconnect()
                if ret == mqtt.MQTT_ERR_SUCCESS:
                    break
            except Exception:
                # Retry to connect in 1 sec up to timeout if set
                sleep(1)
                delay += 1
                self.logger.debug("Retrying to connect in 1 sec")

        if not loop_forever:
            # In case of timeout set, check if it exits because of timeout
            if delay > self.timeout:
                self.logger.error("Unable to reconnect after %s seconds", delay)
                return None

        # Socket must be available once reconnect is successful
        if self._client.socket() is None:
            self.logger.error("Cannot get socket after reconnect")
            return None

        # Set options to new reopened socket
        self._client.socket().setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
        return self._client.socket() 
Example #22
Source File: tsproxy.py    From tsproxy with Apache License 2.0 5 votes vote down vote up
def handle_write(self):
    if self.needs_config:
      self.needs_config = False
      self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
      self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 128 * 1024)
      self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 128 * 1024)
    if len(self.buffer) > 0:
      sent = self.send(self.buffer)
      logging.debug('[{0:d}] TCP => {1:d} byte(s)'.format(self.client_id, sent))
      self.buffer = self.buffer[sent:]
      if self.needs_close and len(self.buffer) == 0:
        self.needs_close = False
        self.handle_close() 
Example #23
Source File: tsproxy.py    From tsproxy with Apache License 2.0 5 votes vote down vote up
def __init__(self, connected_socket, client_id):
    global options
    asyncore.dispatcher.__init__(self, connected_socket)
    self.client_id = client_id
    self.state = self.STATE_WAITING_FOR_HANDSHAKE
    self.ip = None
    self.addresses = None
    self.hostname = None
    self.port = None
    self.requested_address = None
    self.buffer = ''
    self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
    self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 128 * 1024)
    self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 128 * 1024)
    self.needs_close = False 
Example #24
Source File: test_proactor_events.py    From android_universal with MIT License 5 votes vote down vote up
def make_socket(self, cleanup=True):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setblocking(False)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024)
        if cleanup:
            self.addCleanup(sock.close)
        return sock 
Example #25
Source File: test_socket.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def _testTCPClientOption(self, level, option, values):
        sock = None
        try:
            # First listen on a server socket, so that the connection won't be refused.
            server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            server_sock.bind( (HOST, PORT) )
            server_sock.listen(50)
            # Now do the tests
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self._testSetAndGetOption(sock, level, option, values)
            # now connect the socket i.e. cause the implementation socket to be created
            # First bind, so that the SO_REUSEADDR setting propagates
            #sock.bind( (HOST, PORT+1) )
            sock.connect( (HOST, PORT) )
            retrieved_option_value = sock.getsockopt(level, option)
            msg = "TCP client option value '%s'='%s' did not propagate to implementation socket: got %s" % (option, values[-1], retrieved_option_value)
            if option in (socket.SO_RCVBUF, socket.SO_SNDBUF):
                # NOTE: there's no guarantee that bufsize will be the
                # exact setsockopt value, particularly after
                # establishing a connection. seems it will be *at least*
                # the values we test (which are rather small) on
                # BSDs.
                self.assert_(retrieved_option_value >= values[-1], msg)
            else:
                self.failUnlessEqual(retrieved_option_value, values[-1], msg)
            self._testSetAndGetOption(sock, level, option, values)
        finally:
            server_sock.close()
            if sock:
                sock.close()
            pass 
Example #26
Source File: test_socket.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def testSO_SNDBUF(self):
        self.test_udp        = 1
        self.test_tcp_client = 1
        self.test_tcp_server = 1
        self._testOption(socket.SOL_SOCKET, socket.SO_SNDBUF, [1024, 4096, 16384])
        self._testInheritedOption(socket.SOL_SOCKET, socket.SO_SNDBUF, [1024, 4096, 16384]) 
Example #27
Source File: linux.py    From arissploit with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, iface = None, type = ETH_P_ALL, filter=None, nofilter=0):
        if iface is None:
            iface = conf.iface
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0)
        if not nofilter: 
            if conf.except_filter:
                if filter:
                    filter = "(%s) and not (%s)" % (filter, conf.except_filter)
                else:
                    filter = "not (%s)" % conf.except_filter
            if filter is not None:
                attach_filter(self.ins, filter)
        self.ins.bind((iface, type))
        _flush_fd(self.ins)
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
        self.outs = self.ins
        self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30)
        sa_ll = self.outs.getsockname()
        if sa_ll[3] in conf.l2types:
            self.LL = conf.l2types[sa_ll[3]]
        elif sa_ll[1] in conf.l3types:
            self.LL = conf.l3types[sa_ll[1]]
        else:
            self.LL = conf.default_l2
            warning("Unable to guess type (interface=%s protocol=%#x family=%i). Using %s" % (sa_ll[0],sa_ll[1],sa_ll[3],self.LL.name)) 
Example #28
Source File: linux.py    From kamene with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, type = ETH_P_ALL, filter=None, promisc=None, iface=None, nofilter=0):
        self.type = type
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0)
        if iface:
            self.ins.bind((iface, type))
        if not nofilter:
            if conf.except_filter:
                if filter:
                    filter = "(%s) and not (%s)" % (filter, conf.except_filter)
                else:
                    filter = "not (%s)" % conf.except_filter
            if filter is not None:
                attach_filter(self.ins, filter, iface)
        _flush_fd(self.ins)
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
        self.outs = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30)
        if promisc is None:
            promisc = conf.promisc
        self.promisc = promisc
        if self.promisc:
            if iface is None:
                self.iff = get_if_list()
            else:
                if iface.__class__ is list:
                    self.iff = iface
                else:
                    self.iff = [iface]
            for i in self.iff:
                set_promisc(self.ins, i) 
Example #29
Source File: linux.py    From kamene with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, iface = None, type = ETH_P_ALL, filter=None, nofilter=0):
        if iface is None:
            iface = conf.iface
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0)
        if not nofilter: 
            if conf.except_filter:
                if filter:
                    filter = "(%s) and not (%s)" % (filter, conf.except_filter)
                else:
                    filter = "not (%s)" % conf.except_filter
            if filter is not None:
                attach_filter(self.ins, filter, iface)
        self.ins.bind((iface, type))
        _flush_fd(self.ins)
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
        self.outs = self.ins
        self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30)
        sa_ll = self.outs.getsockname()
        if sa_ll[3] in conf.l2types:
            self.LL = conf.l2types[sa_ll[3]]
        elif sa_ll[1] in conf.l3types:
            self.LL = conf.l3types[sa_ll[1]]
        else:
            self.LL = conf.default_l2
            warning("Unable to guess type (interface=%s protocol=%#x family=%i). Using %s" % (sa_ll[0],sa_ll[1],sa_ll[3],self.LL.name)) 
Example #30
Source File: linux.py    From CVE-2016-6366 with MIT License 5 votes vote down vote up
def __init__(self, iface = None, type = ETH_P_ALL, filter=None, nofilter=0):
        if iface is None:
            iface = conf.iface
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0)
        _flush_fd(self.ins)
        if not nofilter: 
            if conf.except_filter:
                if filter:
                    filter = "(%s) and not (%s)" % (filter, conf.except_filter)
                else:
                    filter = "not (%s)" % conf.except_filter
            if filter is not None:
                attach_filter(self.ins, filter)
        self.ins.bind((iface, type))
        self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2**30)
        self.outs = self.ins
        self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2**30)
        sa_ll = self.outs.getsockname()
        if sa_ll[3] in conf.l2types:
            self.LL = conf.l2types[sa_ll[3]]
        elif sa_ll[1] in conf.l3types:
            self.LL = conf.l3types[sa_ll[1]]
        else:
            self.LL = conf.default_l2
            warning("Unable to guess type (interface=%s protocol=%#x family=%i). Using %s" % (sa_ll[0],sa_ll[1],sa_ll[3],self.LL.name))