Python socket.SOCK_STREAM() Examples

The following are 50 code examples for showing how to use socket.SOCK_STREAM(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: pycos   Author: pgiri   File: chat_server.py View Source Project 7 votes vote down vote up
def chat(host, port, task=None):
    task.set_daemon()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock = pycos.AsyncSocket(sock)
    sock.bind((host, port))
    sock.listen(128)
    print('server at %s' % str(sock.getsockname()))

    clients = set()

    try:
        while True:
            conn, addr = yield sock.accept()
            clients.add(conn)
            pycos.Task(client_send, clients, conn)
    except:
        for client in clients:
            client.shutdown(socket.SHUT_RDWR)
            client.close()
        raise 
Example 2
Project: sarafu   Author: pesaply   File: donot.py View Source Project 7 votes vote down vote up
def interact(self):
        from telnetlib import Telnet

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        s.bind((self._revHost, self._revPort))
        s.listen(5)
        cli = s.accept()[0]
        s.close()
        print("[+] Got connect-back")

        t = Telnet()
        t.sock = cli
        t.interact() 
Example 3
Project: pycos   Author: pgiri   File: socket_afile.py View Source Project 6 votes vote down vote up
def client_proc(host, port, input, task=None):
    # client reads input file and sends data in chunks
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock = pycos.AsyncSocket(sock)
    yield sock.connect((host, port))
    # data can be written to this asynchronous socket; however, for
    # illustration, convert its file descriptor to asynchronous file
    # and write to that instead
    afd = pycos.asyncfile.AsyncFile(sock)
    input = open(input)
    csum = hashlib.sha1()
    while True:
        data = os.read(input.fileno(), 16*1024)
        if not data:
            break
        csum.update(data)
        n = yield afd.write(data, full=True)
    afd.close()
    print('client sha1 csum: %s' % csum.hexdigest()) 
Example 4
Project: pycos   Author: pgiri   File: chat_server.py View Source Project 6 votes vote down vote up
def chat(host, port, task=None):
    task.set_daemon()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock = pycos.AsyncSocket(sock)
    sock.bind((host, port))
    sock.listen(128)
    print('server at %s' % str(sock.getsockname()))

    clients = set()

    try:
        while True:
            conn, addr = yield sock.accept()
            clients.add(conn)
            pycos.Task(client_send, clients, conn)
    except:
        for client in clients:
            client.shutdown(socket.SHUT_RDWR)
            client.close()
        raise 
Example 5
Project: pycos   Author: pgiri   File: sock_client.py View Source Project 6 votes vote down vote up
def client(host, port, n, task=None):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock = pycos.AsyncSocket(sock)
    yield sock.connect((host, port))
    print('%s connected' % n)
    # send arbitrary length of data
    msg = '%d: ' % n + '-' * random.randint(100,300) + '/'
    msg = msg.encode()
    yield sock.sendall(msg)
    sock.close()

# pycos.logger.setLevel(pycos.Logger.DEBUG)
# run 10 client tasks 
Example 6
Project: pycos   Author: pgiri   File: socket_afile.py View Source Project 6 votes vote down vote up
def client_proc(host, port, input, task=None):
    # client reads input file and sends data in chunks
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock = pycos.AsyncSocket(sock)
    yield sock.connect((host, port))
    # data can be written to this asynchronous socket; however, for
    # illustration, convert its file descriptor to asynchronous file
    # and write to that instead
    afd = pycos.asyncfile.AsyncFile(sock)
    input = open(input)
    csum = hashlib.sha1()
    while True:
        data = os.read(input.fileno(), 16*1024)
        if not data:
            break
        csum.update(data)
        n = yield afd.write(data, full=True)
    afd.close()
    print('client sha1 csum: %s' % csum.hexdigest()) 
Example 7
Project: pycos   Author: pgiri   File: __init__.py View Source Project 6 votes vote down vote up
def _socketpair():
                if hasattr(socket, 'socketpair'):
                    return socket.socketpair()
                srv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                srv_sock.bind(('127.0.0.1', 0))
                srv_sock.listen(1)
                write_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                try:
                    write_sock.setblocking(False)
                    try:
                        write_sock.connect(srv_sock.getsockname()[:2])
                    except socket.error as e:
                        if e.args[0] in (EINPROGRESS, EWOULDBLOCK):
                            pass
                        else:
                            raise
                    write_sock.setblocking(True)
                    read_sock = srv_sock.accept()[0]
                except:
                    write_sock.close()
                    raise
                finally:
                    srv_sock.close()
                return (read_sock, write_sock) 
Example 8
Project: pycos   Author: pgiri   File: __init__.py View Source Project 6 votes vote down vote up
def _timed_out(self):
                if self._rsock and self._rsock.type & socket.SOCK_STREAM:
                    if self._read_overlap or self._write_overlap:
                        win32file.CancelIo(self._fileno)
                if self._read_task:
                    if self._rsock and self._rsock.type & socket.SOCK_DGRAM:
                        self._notifier.clear(self, _AsyncPoller._Read)
                        self._read_fn = None
                    self._read_task.throw(socket.timeout('timed out'))
                    self._read_result = self._read_task = None
                if self._write_task:
                    if self._rsock and self._rsock.type & socket.SOCK_DGRAM:
                        self._notifier.clear(self, _AsyncPoller._Write)
                        self._write_fn = None
                    self._write_task.throw(socket.timeout('timed out'))
                    self._write_result = self._write_task = None 
Example 9
Project: pycos   Author: pgiri   File: chat_server.py View Source Project 6 votes vote down vote up
def chat(host, port, task=None):
    task.set_daemon()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock = pycos.AsyncSocket(sock)
    sock.bind((host, port))
    sock.listen(128)
    print('server at %s' % str(sock.getsockname()))

    clients = set()

    try:
        while True:
            conn, addr = yield sock.accept()
            clients.add(conn)
            pycos.Task(client_send, clients, conn)
    except:
        for client in clients:
            client.shutdown(socket.SHUT_RDWR)
            client.close()
        raise 
Example 10
Project: pycos   Author: pgiri   File: __init__.py View Source Project 6 votes vote down vote up
def _socketpair():
                if hasattr(socket, 'socketpair'):
                    return socket.socketpair()
                srv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                srv_sock.bind(('127.0.0.1', 0))
                srv_sock.listen(1)
                write_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                try:
                    write_sock.setblocking(False)
                    try:
                        write_sock.connect(srv_sock.getsockname()[:2])
                    except socket.error as e:
                        if e.args[0] in (EINPROGRESS, EWOULDBLOCK):
                            pass
                        else:
                            raise
                    write_sock.setblocking(True)
                    read_sock = srv_sock.accept()[0]
                except:
                    write_sock.close()
                    raise
                finally:
                    srv_sock.close()
                return (read_sock, write_sock) 
Example 11
Project: gluster-georep-tools   Author: aravindavk   File: cli.py View Source Project 6 votes vote down vote up
def is_port_enabled(hostname, port):
    """
    To check if a port is enabled or not. For example
    To check ssh port is enabled or not,
        is_port_enabled(HOSTNAME, 22)

    To see glusterd port is enabled,
        is_port_enabled(HOSTNAME, 24007)
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((hostname, port))
        enabled = True
    except socket.error:
        enabled = False

    s.close()
    return enabled 
Example 12
Project: charm-plumgrid-gateway   Author: openstack   File: rpdb.py View Source Project 6 votes vote down vote up
def __init__(self, addr="127.0.0.1", port=4444):
        """Initialize the socket and initialize pdb."""

        # Backup stdin and stdout before replacing them by the socket handle
        self.old_stdout = sys.stdout
        self.old_stdin = sys.stdin

        # Open a 'reusable' socket to let the webapp reload on the same port
        self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.skt.bind((addr, port))
        self.skt.listen(1)
        (clientsocket, address) = self.skt.accept()
        handle = clientsocket.makefile('rw')
        pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle)
        sys.stdout = sys.stdin = handle 
Example 13
Project: NS_Proj   Author: drstarry   File: base.py View Source Project 6 votes vote down vote up
def Start(self, serverAddress, serverPort, bruteforce_file):
        """
        serverHost = string: localhost/ip address/url for server
        serverPort = int: port number to connect for server
        bruteforce_file = string: name of the file that has password guesses
        """
        serverSckt = socket(AF_INET, SOCK_STREAM)
        serverSckt.connect((serverAddress, serverPort))
        print "Client: Connected to Server at %s:%d" \
            % (serverAddress, serverPort)

        success, time_taken, attempts = self.Client(serverSckt, bruteforce_file)
        # used to close socket when client is done
        serverSckt.sendCloseSignal()

        if success:
            print "Success! Cracked the password and got in."
        else:
            print "Failure! Tried to get in but couldn't."

        print "Took %d guesses and %d seconds." \
            % (attempts, time_taken.seconds)

        serverSckt.shutdown(1)  # send close signal to server socket
        serverSckt.close()  # close connection 
Example 14
Project: NS_Proj   Author: drstarry   File: base.py View Source Project 6 votes vote down vote up
def Start(self, serverAddress, serverPort, password_file):
        """
        serverAddress = string: localhost/ip address/url
        serverPort = int: port number to run server
        password_file = string: file that contains username/password pairs
        """
        serverSckt = socket(AF_INET, SOCK_STREAM)
        serverSckt.bind((serverAddress, serverPort))
        serverSckt.listen(1)  # await requests
        print "Server: Listening at %s:%d" % (serverAddress, serverPort)
        sckt, addr = serverSckt.accept()  # accept a connection (blocking)

        self.Host(sckt, password_file)

        sckt.shutdown(1)  # send close signal
        sckt.close()  # close connection 
Example 15
Project: charm-swift-proxy   Author: openstack   File: rpdb.py View Source Project 6 votes vote down vote up
def __init__(self, addr="127.0.0.1", port=4444):
        """Initialize the socket and initialize pdb."""

        # Backup stdin and stdout before replacing them by the socket handle
        self.old_stdout = sys.stdout
        self.old_stdin = sys.stdin

        # Open a 'reusable' socket to let the webapp reload on the same port
        self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.skt.bind((addr, port))
        self.skt.listen(1)
        (clientsocket, address) = self.skt.accept()
        handle = clientsocket.makefile('rw')
        pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle)
        sys.stdout = sys.stdin = handle 
Example 16
Project: Picamera   Author: loadstarCN   File: socket_client.py View Source Project 6 votes vote down vote up
def Send_File_Client():
    sendSock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sendSock.connect(ADDR)

    fhead=struct.pack('IdI',1,float(time.time()),os.stat(filename).st_size)
    print(fhead)
    sendSock.send(fhead)
    fp = open(filename,'rb')

    while 1:
        filedata = fp.read(BUFSIZE)
        if not filedata: 
            break
        sendSock.send(filedata)
    
    '''
    print u"?????????????...\n"

    fp.close()
    sendSock.close()
    print u"?????...\n" 

    ''' 
Example 17
Project: socket-http   Author: thisforeda   File: httpx.py View Source Project 6 votes vote down vote up
def send(self,send_data):
        if self.__is_addr_reset or \
                         self._is_close_for_invoker or \
                                               self.__is_connection_closed():
            self.__connection = socket(AF_INET,SOCK_STREAM)

            if self.__is_ssl:
                self.__connection = ssl.wrap_socket(self.__connection)
                
            try :
                self.__connection.connect(self.__addr)
                
                self.__connection.settimeout(self.__timeout)
                
                self._is_close_for_invoker = False
                self.__is_addr_reset = False
                
            except Exception as exception:
                self.__recorder.write(
                    'Cannot connect %s' % str(self.__addr),
                    Exception = str(exception))
                return None
            
        self.__connection.send(send_data)
        return self 
Example 18
Project: kinect-2-libras   Author: inessadl   File: smtpd.py View Source Project 6 votes vote down vote up
def __init__(self, localaddr, remoteaddr):
        self._localaddr = localaddr
        self._remoteaddr = remoteaddr
        asyncore.dispatcher.__init__(self)
        try:
            self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
            # try to re-use a server port if possible
            self.set_reuse_addr()
            self.bind(localaddr)
            self.listen(5)
        except:
            # cleanup asyncore.socket_map before raising
            self.close()
            raise
        else:
            print >> DEBUGSTREAM, \
                  '%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % (
                self.__class__.__name__, time.ctime(time.time()),
                localaddr, remoteaddr) 
Example 19
Project: kinect-2-libras   Author: inessadl   File: smtplib.py View Source Project 6 votes vote down vote up
def connect(self, host='localhost', port=0):
        """Connect to the LMTP daemon, on either a Unix or a TCP socket."""
        if host[0] != '/':
            return SMTP.connect(self, host, port)

        # Handle Unix-domain sockets.
        try:
            self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.sock.connect(host)
        except socket.error, msg:
            if self.debuglevel > 0:
                print>>stderr, 'connect fail:', host
            if self.sock:
                self.sock.close()
            self.sock = None
            raise socket.error, msg
        (code, msg) = self.getreply()
        if self.debuglevel > 0:
            print>>stderr, "connect:", msg
        return (code, msg)


# Test the sendmail method, which tests most of the others.
# Note: This always sends to localhost. 
Example 20
Project: kinect-2-libras   Author: inessadl   File: handlers.py View Source Project 6 votes vote down vote up
def __init__(self, address=('localhost', SYSLOG_UDP_PORT),
                 facility=LOG_USER, socktype=socket.SOCK_DGRAM):
        """
        Initialize a handler.

        If address is specified as a string, a UNIX socket is used. To log to a
        local syslogd, "SysLogHandler(address="/dev/log")" can be used.
        If facility is not specified, LOG_USER is used.
        """
        logging.Handler.__init__(self)

        self.address = address
        self.facility = facility
        self.socktype = socktype

        if isinstance(address, basestring):
            self.unixsocket = 1
            self._connect_unixsocket(address)
        else:
            self.unixsocket = 0
            self.socket = socket.socket(socket.AF_INET, socktype)
            if socktype == socket.SOCK_STREAM:
                self.socket.connect(address)
        self.formatter = None 
Example 21
Project: kinect-2-libras   Author: inessadl   File: webbrowser.py View Source Project 6 votes vote down vote up
def _find_grail_rc(self):
        import glob
        import pwd
        import socket
        import tempfile
        tempdir = os.path.join(tempfile.gettempdir(),
                               ".grail-unix")
        user = pwd.getpwuid(os.getuid())[0]
        filename = os.path.join(tempdir, user + "-*")
        maybes = glob.glob(filename)
        if not maybes:
            return None
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        for fn in maybes:
            # need to PING each one until we find one that's live
            try:
                s.connect(fn)
            except socket.error:
                # no good; attempt to clean it out, but don't fail:
                try:
                    os.unlink(fn)
                except IOError:
                    pass
            else:
                return s 
Example 22
Project: kinect-2-libras   Author: inessadl   File: poplib.py View Source Project 6 votes vote down vote up
def __init__(self, host, port = POP3_SSL_PORT, keyfile = None, certfile = None):
            self.host = host
            self.port = port
            self.keyfile = keyfile
            self.certfile = certfile
            self.buffer = ""
            msg = "getaddrinfo returns an empty list"
            self.sock = None
            for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):
                af, socktype, proto, canonname, sa = res
                try:
                    self.sock = socket.socket(af, socktype, proto)
                    self.sock.connect(sa)
                except socket.error, msg:
                    if self.sock:
                        self.sock.close()
                    self.sock = None
                    continue
                break
            if not self.sock:
                raise socket.error, msg
            self.file = self.sock.makefile('rb')
            self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
            self._debugging = 0
            self.welcome = self._getresp() 
Example 23
Project: LFISuite   Author: D35m0nd142   File: socks.py View Source Project 6 votes vote down vote up
def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, *args, **kwargs):
        if type not in (socket.SOCK_STREAM, socket.SOCK_DGRAM):
            msg = "Socket type must be stream or datagram, not {!r}"
            raise ValueError(msg.format(type))

        super(socksocket, self).__init__(family, type, proto, *args, **kwargs)
        self._proxyconn = None  # TCP connection to keep UDP relay alive

        if self.default_proxy:
            self.proxy = self.default_proxy
        else:
            self.proxy = (None, None, None, None, None, None)
        self.proxy_sockname = None
        self.proxy_peername = None

        self._timeout = None 
Example 24
Project: yeelight-controller   Author: kevinxw   File: YeelightWifiBulbLanCtrl.py View Source Project 6 votes vote down vote up
def operate_on_bulb(idx, method, params):
  '''
  Operate on bulb; no gurantee of success.
  Input data 'params' must be a compiled into one string.
  E.g. params="1"; params="\"smooth\"", params="1,\"smooth\",80"
  '''
  if not bulb_idx2ip.has_key(idx):
    print "error: invalid bulb idx"
    return
  
  bulb_ip=bulb_idx2ip[idx]
  port=detected_bulbs[bulb_ip][5]
  try:
    tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print "connect ",bulb_ip, port ,"..."
    tcp_socket.connect((bulb_ip, int(port)))
    msg="{\"id\":" + str(next_cmd_id()) + ",\"method\":\""
    msg += method + "\",\"params\":[" + params + "]}\r\n"
    tcp_socket.send(msg)
    tcp_socket.close()
  except Exception as e:
    print "Unexpected error:", e 
Example 25
Project: PyJFuzz   Author: mseclab   File: pjf_testcase_server.py View Source Project 6 votes vote down vote up
def send_testcase(json, ip, port):
        """
        Send a raw testcase
        """
        try:
            json = struct.pack("<I", len(json)) + json
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.connect((ip, int(port)))
                s.send(json)
                s.shutdown(socket.SHUT_RDWR)
                s.close()
                return True
            except socket.error:
                return False
        except socket.error as e:
            raise PJFSocketError(e.message if hasattr(e, "message") else str(e))
        except Exception as e:
            raise  PJFBaseException(e.message) 
Example 26
Project: F-Scrack   Author: y1ng1996   File: F-Scrack.py View Source Project 6 votes vote down vote up
def redis(self,user,pass_):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((self.ip,int(self.port)))
            s.send("INFO\r\n")
            result = s.recv(1024)
            if "redis_version" in result:
                return "unauthorized"
            elif "Authentication" in result:
                for pass_ in PASSWORD_DIC:
                    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    s.connect((self.ip,int(self.port)))
                    s.send("AUTH %s\r\n"%(pass_))
                    result = s.recv(1024)
                    if '+OK' in result:
                        return "username:%s,password:%s" % (user,pass_)
        except Exception,e:
            return 3 
Example 27
Project: F-Scrack   Author: y1ng1996   File: F-Scrack.py View Source Project 6 votes vote down vote up
def mongodb(self,user,pass_):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((self.ip,int(self.port)))
            data = binascii.a2b_hex("3a000000a741000000000000d40700000000000061646d696e2e24636d640000000000ffffffff130000001069736d6173746572000100000000")
            s.send(data)
            result = s.recv(1024)
            if "ismaster" in result:
                getlog_data = binascii.a2b_hex("480000000200000000000000d40700000000000061646d696e2e24636d6400000000000100000021000000026765744c6f670010000000737461727475705761726e696e67730000")
                s.send(getlog_data)
                result = s.recv(1024)
                if "totalLinesWritten" in result:
                    return "unauthorized"
                else:return 3
        except Exception,e:
            return 3 
Example 28
Project: F-Scrack   Author: y1ng1996   File: F-Scrack.py View Source Project 6 votes vote down vote up
def scan_port(host,port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((str(host),int(port)))
        log('portscan',host,port)
    except Exception,e:
        return False
    try:
        data = sock.recv(512)
        if len(data) > 2:
            return data
        else:
            sock.send('a\n\n')
            data = sock.recv(512)
            sock.close()
            if len(data) > 2:
                return data
            else:
                return 'NULL'
    except Exception,e:
        sock.close()
        return 'NULL' 
Example 29
Project: pscheduler   Author: perfsonar   File: api.py View Source Project 6 votes vote down vote up
def api_has_bwctl(host, timeout=5, bind=None):
    """
    Determine if a host is running the BWCTL daemon
    """

    # Null implies localhost
    if host is None:
        host = "localhost"

    # HACK: BWTCLBC
    # If the environment says to bind to a certain address, do it.
    if bind is None:
        bind = os.environ.get('PSCHEDULER_LEAD_BIND_HACK', None)

    for family in [socket.AF_INET, socket.AF_INET6]:
        try:
            with closing(socket.socket(family, socket.SOCK_STREAM)) as sock:
                if bind is not None:
                    sock.bind((bind, 0))
                sock.settimeout(timeout)
                return sock.connect_ex((host, 4823)) == 0
        except socket.error:
            pass

    return False 
Example 30
Project: routerPWN   Author: lilloX   File: classes.py View Source Project 6 votes vote down vote up
def __is_open (self, port):
		s = socket.socket()
		try:
			s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			s.settimeout(1)
			r = s.connect_ex((self.ip, int(port)))
			if r == 0:
				s.close()
				return 1
			s.close()
			return 0
		except:
			s.close()
			return 0

	# Check if there is a running a webserver and if it is know 
Example 31
Project: PyFlooder   Author: D4Vinci   File: pyflooder.py View Source Project 6 votes vote down vote up
def attack():

    ip = socket.gethostbyname( host )
    global n
    msg=str(string.letters+string.digits+string.punctuation)
    data="".join(random.sample(msg,5))
    dos = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        n+=1
        dos.connect((ip, port))
        dos.send( "GET /%s HTTP/1.1\r\n" % data )
        print "\n "+time.ctime().split(" ")[3]+" "+"["+str(n)+"] #-#-# Hold Your Tears #-#-#"

    except socket.error:
        print "\n [ No connection! Server maybe down ] "

    dos.close() 
Example 32
Project: deb-python-cassandra-driver   Author: openstack   File: policies.py View Source Project 6 votes vote down vote up
def __init__(self, hosts):
        """
        The `hosts` parameter should be a sequence of hosts to permit
        connections to.
        """
        msg = ('WhiteListRoundRobinPolicy is deprecated. '
               'It will be removed in 4.0. '
               'It can effectively be reimplemented using HostFilterPolicy.')
        warn(msg, DeprecationWarning)
        # DeprecationWarnings are silent by default so we also log the message
        log.warning(msg)

        self._allowed_hosts = hosts
        self._allowed_hosts_resolved = [endpoint[4][0] for a in self._allowed_hosts
                                        for endpoint in socket.getaddrinfo(a, None, socket.AF_UNSPEC, socket.SOCK_STREAM)]

        RoundRobinPolicy.__init__(self) 
Example 33
Project: Projects   Author: it2school   File: rest.py View Source Project 6 votes vote down vote up
def create_connection(address):
    host, port = address
    err = None
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
        af, socktype, proto, _, sa = res
        sock = None
        try:
            sock = socket.socket(af, socktype, proto)
            sock.connect(sa)
            return sock

        except socket.error as e:
            err = e
            if sock is not None:
                sock.close()

    if err is not None:
        raise err  # pylint: disable=raising-bad-type
    else:
        raise socket.error("getaddrinfo returns an empty list") 
Example 34
Project: code   Author: ActiveState   File: recipe-213238.py View Source Project 6 votes vote down vote up
def get_proxy(self):
        if not self._ptype:
            proxy=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            proxy.connect((self._phost,self._pport))
            proxy_authorization=''
            if self._puser:
                proxy_authorization='Proxy-authorization: Basic '+\
                base64.encodestring(self._puser+':'+self._ppass).strip()+'\r\n'
            proxy_connect='CONNECT %s:%sHTTP/1.0\r\n'%(self.host,self._port)
            user_agent='User-Agent: pytunnel\r\n'
            proxy_pieces=proxy_connect+proxy_authorization+user_agent+'\r\n'
            proxy.sendall(proxy_pieces+'\r\n')
            response=recv_all(proxy,timeout=0.5)
            status=response.split()[1]
            if int(status)/100 !=2:
                print 'error',response
                raise status
            return proxy 
Example 35
Project: shadowsocksR-b   Author: hao35954514   File: tcprelay.py View Source Project 6 votes vote down vote up
def _socket_bind_addr(self, sock, af):
        bind_addr = ''
        if self._bind and af == socket.AF_INET:
            bind_addr = self._bind
        elif self._bindv6 and af == socket.AF_INET6:
            bind_addr = self._bindv6
        else:
            bind_addr = self._accept_address[0]

        bind_addr = bind_addr.replace("::ffff:", "")
        if bind_addr in self._ignore_bind_list:
            bind_addr = None
        if bind_addr:
            local_addrs = socket.getaddrinfo(bind_addr, 0, 0, socket.SOCK_STREAM, socket.SOL_TCP)
            if local_addrs[0][0] == af:
                logging.debug("bind %s" % (bind_addr,))
                try:
                    sock.bind((bind_addr, 0))
                except Exception as e:
                    logging.warn("bind %s fail" % (bind_addr,)) 
Example 36
Project: charm-keystone   Author: openstack   File: rpdb.py View Source Project 6 votes vote down vote up
def __init__(self, addr="127.0.0.1", port=4444):
        """Initialize the socket and initialize pdb."""

        # Backup stdin and stdout before replacing them by the socket handle
        self.old_stdout = sys.stdout
        self.old_stdin = sys.stdin

        # Open a 'reusable' socket to let the webapp reload on the same port
        self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.skt.bind((addr, port))
        self.skt.listen(1)
        (clientsocket, address) = self.skt.accept()
        handle = clientsocket.makefile('rw')
        pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle)
        sys.stdout = sys.stdin = handle 
Example 37
Project: charm-keystone   Author: openstack   File: rpdb.py View Source Project 6 votes vote down vote up
def __init__(self, addr="127.0.0.1", port=4444):
        """Initialize the socket and initialize pdb."""

        # Backup stdin and stdout before replacing them by the socket handle
        self.old_stdout = sys.stdout
        self.old_stdin = sys.stdin

        # Open a 'reusable' socket to let the webapp reload on the same port
        self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.skt.bind((addr, port))
        self.skt.listen(1)
        (clientsocket, address) = self.skt.accept()
        handle = clientsocket.makefile('rw')
        pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle)
        sys.stdout = sys.stdin = handle 
Example 38
Project: charm-keystone   Author: openstack   File: rpdb.py View Source Project 6 votes vote down vote up
def __init__(self, addr="127.0.0.1", port=4444):
        """Initialize the socket and initialize pdb."""

        # Backup stdin and stdout before replacing them by the socket handle
        self.old_stdout = sys.stdout
        self.old_stdin = sys.stdin

        # Open a 'reusable' socket to let the webapp reload on the same port
        self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.skt.bind((addr, port))
        self.skt.listen(1)
        (clientsocket, address) = self.skt.accept()
        handle = clientsocket.makefile('rw')
        pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle)
        sys.stdout = sys.stdin = handle 
Example 39
Project: charm-keystone   Author: openstack   File: rpdb.py View Source Project 6 votes vote down vote up
def __init__(self, addr="127.0.0.1", port=4444):
        """Initialize the socket and initialize pdb."""

        # Backup stdin and stdout before replacing them by the socket handle
        self.old_stdout = sys.stdout
        self.old_stdin = sys.stdin

        # Open a 'reusable' socket to let the webapp reload on the same port
        self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.skt.bind((addr, port))
        self.skt.listen(1)
        (clientsocket, address) = self.skt.accept()
        handle = clientsocket.makefile('rw')
        pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle)
        sys.stdout = sys.stdin = handle 
Example 40
Project: ParadoxIP150v2   Author: Tertiush   File: client.py View Source Project 6 votes vote down vote up
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("localhost", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2) 
Example 41
Project: ParadoxIP150v2   Author: Tertiush   File: IP150-MQTTv2.py View Source Project 6 votes vote down vote up
def connect_ip150socket(address, port):
    try:
        print "trying to connect %s" % address
        logging.info("Connecting to %s" % address)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(2)
        s.connect((address, port))
        print "connected"
    except Exception, e:
        logging.error( "Error connecting to IP module (exiting): " + repr(e))
        print "error connecting"
        client.publish(Topic_Publish_AppState,
                       "Error connecting to IP module (exiting): " + repr(e),
                       0, True)
        sys.exit()

    return s 
Example 42
Project: swjtu-pyscraper   Author: Desgard   File: serving.py View Source Project 6 votes vote down vote up
def select_ip_version(host, port):
    """Returns AF_INET4 or AF_INET6 depending on where to connect to."""
    # disabled due to problems with current ipv6 implementations
    # and various operating systems.  Probably this code also is
    # not supposed to work, but I can't come up with any other
    # ways to implement this.
    # try:
    #     info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
    #                               socket.SOCK_STREAM, 0,
    #                               socket.AI_PASSIVE)
    #     if info:
    #         return info[0][0]
    # except socket.gaierror:
    #     pass
    if ':' in host and hasattr(socket, 'AF_INET6'):
        return socket.AF_INET6
    return socket.AF_INET 
Example 43
Project: iot   Author: akademikbilisim   File: luatool.py View Source Project 6 votes vote down vote up
def __init__(self, host, port):
        self.host = host
        self.port = port
        self.socket = None

        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error as e:
            raise TransportError(e.strerror)

        try:
            self.socket.connect((host, port))
        except socket.error as e:
            raise TransportError(e.strerror)
        # read intro from telnet server (see telnet_srv.lua)
        self.socket.recv(50) 
Example 44
Project: pycos   Author: pgiri   File: sock_client.py View Source Project 5 votes vote down vote up
def client(host, port, n, task=None):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock = pycos.AsyncSocket(sock)
    yield sock.connect((host, port))
    print('%s connected' % n)
    # send arbitrary length of data
    msg = '%d: ' % n + '-' * random.randint(100,300) + '/'
    msg = msg.encode()
    yield sock.sendall(msg)
    sock.close()

# pycos.logger.setLevel(pycos.Logger.DEBUG)
# run 10 client tasks 
Example 45
Project: pycos   Author: pgiri   File: sock_server.py View Source Project 5 votes vote down vote up
def server(host, port, task=None):
    task.set_daemon()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # setup socket for asynchronous I/O with pycos
    sock = pycos.AsyncSocket(sock)
    sock.bind((host, port))
    sock.listen(128)

    while True:
        conn, addr = yield sock.accept()
        # create a task to process connection
        pycos.Task(process, conn)

# pycos.logger.setLevel(pycos.Logger.DEBUG) 
Example 46
Project: pycos   Author: pgiri   File: webserver.py View Source Project 5 votes vote down vote up
def server(host, port, task=None):
    task.set_daemon()
    sock = pycos.AsyncSocket(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((host, port))
    sock.listen(5000)

    while True:
        conn, addr = yield sock.accept()
        pycos.Task(process, conn) 
Example 47
Project: pycos   Author: pgiri   File: sock_server.py View Source Project 5 votes vote down vote up
def server(host, port, task=None):
    task.set_daemon()
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # setup socket for asynchronous I/O with pycos
    sock = pycos.AsyncSocket(sock)
    sock.bind((host, port))
    sock.listen(128)

    while True:
        conn, addr = yield sock.accept()
        # create a task to process connection
        pycos.Task(process, conn)

# pycos.logger.setLevel(pycos.Logger.DEBUG) 
Example 48
Project: pycos   Author: pgiri   File: webserver.py View Source Project 5 votes vote down vote up
def server(host, port, task=None):
    task.set_daemon()
    sock = pycos.AsyncSocket(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((host, port))
    sock.listen(5000)

    while True:
        conn, addr = yield sock.accept()
        pycos.Task(process, conn) 
Example 49
Project: pycos   Author: pgiri   File: __init__.py View Source Project 5 votes vote down vote up
def _register(self):
                if not self._blocking:
                    if self._rsock.type & socket.SOCK_STREAM:
                        self._read_overlap = pywintypes.OVERLAPPED()
                        self._write_overlap = pywintypes.OVERLAPPED()
                        self._notifier.register(self._fileno)
                    else:
                        self._notifier = self._notifier.async_poller
                else:
                    _AsyncSocket._register(self) 
Example 50
Project: pycos   Author: pgiri   File: __init__.py View Source Project 5 votes vote down vote up
def _unregister(self):
                if self._notifier:
                    self._notifier.unregister(self)
                    if self._rsock.type & socket.SOCK_STREAM:
                        if ((self._read_overlap and self._read_overlap.object) or
                           (self._write_overlap and self._write_overlap.object)):
                            def _cleanup_(rc, n):
                                self._read_overlap.object = self._write_overlap.object = None
                                self._read_result = self._write_result = None
                                self._read_task = self._write_task = None
                                self._read_overlap = self._write_overlap = None
                                self._notifier = None
                                # if rc and rc != winerror.ERROR_OPERATION_ABORTED:
                                #     logger.warning('CancelIo failed?: %x', rc)
                            if self._read_overlap and self._read_overlap.object:
                                self._read_overlap.object = _cleanup_
                            if self._write_overlap and self._write_overlap.object:
                                self._read_overlap.object = _cleanup_
                            rc = win32file.CancelIo(self._fileno)
                            if rc:
                                logger.warning('CancelIo request failed: %d', rc)
                        else:
                            self._read_overlap = self._write_overlap = None
                            self._read_result = self._write_result = None
                            self._read_task = self._write_task = None
                            self._notifier = None
                    else:
                        self._notifier = None