Python socket.SOCK_STREAM Examples

The following are 30 code examples for showing how to use socket.SOCK_STREAM(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module socket , or try the search function .

Example 1
Project: Starx_Pixiv_Collector   Author: SuzukiHonoka   File: start.py    License: MIT License 7 votes vote down vote up
def ip_latency_test(ip, port=443):
    tag = 'IP_Latency_TEST'
    print_with_tag(tag, ['Prepare IP latency test for ip', ip, 'Port', str(port)])
    s_test = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s_test.settimeout(10)
    s_start = time.time()
    try:
        s_test.connect((ip, port))
        s_test.shutdown(socket.SHUT_RD)
    except Exception as e:
        print_with_tag(tag, ['Error:', e])
        return None
    s_stop = time.time()
    s_runtime = '%.2f' % (1000 * (s_stop - s_start))
    print_with_tag(tag, [ip, 'Latency:', s_runtime])
    return float(s_runtime) 
Example 2
Project: RF-Monitor   Author: EarToEarOak   File: server.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, eventHandler):
        threading.Thread.__init__(self)
        self.name = 'Server'
        self.daemon = True
        self._eventHandler = eventHandler

        self._client = None
        self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        try:
            self._server.bind(('', PORT))
            self._server.listen(5)
        except socket.error:
            event = Event(Events.SCAN_ERROR, msg='Could not start server')
            post_event(eventHandler, event)
            return

        self._cancel = False
        self.start() 
Example 3
Project: ALF   Author: blackberry   File: SockPuppet.py    License: Apache License 2.0 6 votes vote down vote up
def connect(self):
        if self.is_server:
            log.debug("waiting for client to connect...")
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind(('', self.port))
            s.settimeout(0.1)
            start_time = time.time()
            s.listen(0)
            while True:
                try:
                    conn, _ = s.accept()
                    self.conn = conn
                    break
                except socket.timeout:
                    pass
                if self.timeout > 0 and time.time() - start_time >= self.timeout:
                    s.close()
                    raise RuntimeError("Timeout exceeded (%ds)" % self.timeout)
            self.conn.setblocking(True)
        else:
            log.debug("connecting to server (%s:%d)...", self.ip, self.port)
            self.conn = socket.create_connection((self.ip, self.port), self.timeout) 
Example 4
Project: iSDX   Author: sdn-ixp   File: sdnip.py    License: Apache License 2.0 6 votes vote down vote up
def config(self, **kwargs):
        super(BgpRouter, self).config(**kwargs)

        self.cmd('%s/zebra -d -f %s -z %s -i %s'
                 % (BgpRouter.binDir, self.zebraConfFile, self.socket, self.zebraPidFile))
        while True:
            try:
                s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # @UndefinedVariable
                s.connect(self.socket)
                #print 'connected - breaking'
                s.close()
                break
            except Exception, e:
                #print' ERROR: ' + repr(e)
                time.sleep(.1)
        #print 'zebra ready' 
Example 5
Project: iSDX   Author: sdn-ixp   File: tnode.py    License: Apache License 2.0 6 votes vote down vote up
def create_command_listener (baddr, port):
    try:
        if port is None:
            try:
                if os.path.exists(baddr):
                    os.unlink(baddr)
            except OSError:
                print 'could not remove old unix socket ' + baddr
                return
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # @UndefinedVariable
            s.bind(baddr)
        else:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind((baddr, int(port)))
    except socket.error , msg:
        print 'Bind failed on command interface ' + baddr + ' port ' + str(port) + ' Error Code : ' + str(msg[0]) + ' Message ' + msg[1] + '\n'
        return 
Example 6
Project: iSDX   Author: sdn-ixp   File: tmgr.py    License: Apache License 2.0 6 votes vote down vote up
def connect (host, why):    
    # should be either a listener host or a router host (edge-router)
    if host not in bgprouters and host not in hosts and host not in participants:
            log.error('MM:' + host + ' ERROR: ' + why + ': Unknown host: ' + host)
            return None    
    try:
        hostdata = hosts[host]
    except:
        try:
            hostdata = bgprouters[host]
        except:
            hostdata = participants[host]

    #print 'MM:' + host + ' INFO: ' + why + ': Connecting to ' + host + ' at ' + hostdata.host + ':' + str(hostdata.port)

    try:
        if hostdata.port is None:
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # @UndefinedVariable
            s.connect(hostdata.host)
        else:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((hostdata.host, int(hostdata.port)))
    except Exception, e:
        log.error('MM:' + host + ' ERROR: ' + why + ': ' + repr(e))
        return None 
Example 7
Project: iSDX   Author: sdn-ixp   File: tmgr.py    License: Apache License 2.0 6 votes vote down vote up
def genericObjNW (host, label, cmd):
    
    if host not in participants:
            log.error('MM:' + host + ' ERROR: ' + label + ': Can only send to a participant: ' + host)
            return None    
    try:
        hostdata = hosts[host]
    except:
        try:
            hostdata = bgprouters[host]
        except:
            hostdata = participants[host]

    #print 'MM:' + host + ' INFO: ' + why + ': Connecting to ' + host + ' at ' + hostdata.host + ':' + str(hostdata.port)

    try:
        if hostdata.port is None:
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # @UndefinedVariable
            s.connect(hostdata.host)
        else:
            s = Client((hostdata.host, int(hostdata.port)))
    except Exception, e:
        log.error('MM:' + host + ' ERROR: ' + label + ': ' + repr(e))
        return None 
Example 8
Project: The-chat-room   Author: 11ze   File: client-test2.py    License: MIT License 6 votes vote down vote up
def fileGet(name):
    PORT3 = 50009
    ss2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ss2.connect((IP, PORT3))
    message = 'get ' + name
    ss2.send(message.encode())
    fileName = '.\\Client_image_cache\\' + name
    print('Start downloading image!')
    print('Waiting.......')
    with open(fileName, 'wb') as f:
        while True:
            data = ss2.recv(1024)
            if data == 'EOF'.encode():
                print('Download completed!')
                break
            f.write(data)
    time.sleep(0.1)
    ss2.send('quit'.encode())


# 将图片上传到图片服务端的缓存文件夹中 
Example 9
Project: The-chat-room   Author: 11ze   File: client-test.py    License: MIT License 6 votes vote down vote up
def fileGet(name):
    PORT3 = 50009
    ss2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ss2.connect((IP, PORT3))
    message = 'get ' + name
    ss2.send(message.encode())
    fileName = '.\\Client_image_cache\\' + name
    print('Start downloading image!')
    print('Waiting.......')
    with open(fileName, 'wb') as f:
        while True:
            data = ss2.recv(1024)
            if data == 'EOF'.encode():
                print('Download completed!')
                break
            f.write(data)
    time.sleep(0.1)
    ss2.send('quit'.encode())


# 将图片上传到图片服务端的缓存文件夹中 
Example 10
Project: XFLTReaT   Author: earthquake   File: TCP_generic.py    License: MIT License 6 votes vote down vote up
def stop(self):
		self._stop = True

		if self.threads:
			for t in self.threads:
				t.stop()
		
		# not so nice solution to get rid of the block of listen()
		# unfortunately close() does not help on the block
		try:
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			serverbind = self.config.get("Global", "serverbind")
			if serverbind == "0.0.0.0":
				# windows does not like to connect to 0.0.0.0
				serverbind = "127.0.0.1"

			server_socket.connect((serverbind, int(self.config.get(self.get_module_configname(), "serverport"))))
		except:
			pass

		return 
Example 11
Project: XFLTReaT   Author: earthquake   File: TCP_generic.py    License: MIT License 6 votes vote down vote up
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			server_socket.settimeout(3)
			server_socket.connect((self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport"))))
			client_fake_thread = TCP_generic_thread(0, 0, None, None, server_socket, None, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
			client_fake_thread.do_check()
			client_fake_thread.communication(True)

			self.cleanup(server_socket)

		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)
		except socket.error as exception:
			if exception.args[0] == 111:
				common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			else:
				common.internal_print("Connection error: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)

		return 
Example 12
Project: XFLTReaT   Author: earthquake   File: interface.py    License: MIT License 6 votes vote down vote up
def mac_set_ip_address(self, dev, ip, serverip, netmask):
		ifr = struct.pack('<16sBBHIIIBBHIIIBBHIII',
			self.iface_name,
			16, socket.AF_INET, 0, struct.unpack('<L', socket.inet_pton(socket.AF_INET, ip))[0], 0, 0,
			16, socket.AF_INET, 0, struct.unpack('<L', socket.inet_pton(socket.AF_INET, serverip))[0], 0, 0,
			16, 0, 0, struct.unpack('<L', socket.inet_pton(socket.AF_INET, "255.255.255.255"))[0], 0, 0)
		try:
			sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			fcntl.ioctl(sock, self.IOCTL_MACOSX_SIOCAIFADDR, ifr)
		except Exception as e:
			common.internal_print("Something went wrong with setting up the interface.", -1)
			print(e)
			sys.exit(-1)

		# adding new route for forwarding packets properly.
		integer_ip = struct.unpack(">I", socket.inet_pton(socket.AF_INET, serverip))[0]
		rangeip = socket.inet_ntop(socket.AF_INET, struct.pack(">I", integer_ip & ((2**int(netmask))-1)<<32-int(netmask)))
		ps = subprocess.Popen(["route", "add", "-net", rangeip+"/"+netmask, serverip], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		(stdout, stderr) = ps.communicate()
		if stderr:
			if not "File exists" in stderr:
				common.internal_print("Error: adding client route: {0}".format(stderr), -1)
				sys.exit(-1)

		return 
Example 13
Project: XFLTReaT   Author: earthquake   File: interface.py    License: MIT License 6 votes vote down vote up
def freebsd_tun_alloc(self, dev, flags):
		try:
			sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			ifr = struct.pack('<16si', 'tun', 0)
			self.iface_name = fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCIFCREATE2, ifr)
			self.iface_name = self.iface_name.rstrip("\x00")

			buff = array.array('c', dev+"\x00")
			caddr_t, _ = buff.buffer_info()
			ifr = struct.pack('16sP', self.iface_name, caddr_t);

			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCSIFNAME, ifr)
			tun = os.open("/dev/"+self.iface_name, os.O_RDWR | os.O_NONBLOCK)
			self.iface_name = dev

		except IOError as e:
			print e
			common.internal_print("Error: Cannot create tunnel. Is {0} in use?".format(dev), -1)
			sys.exit(-1)

		return tun 
Example 14
Project: InsightAgent   Author: insightfinder   File: script_runner.py    License: Apache License 2.0 6 votes vote down vote up
def acceptThread(parameters):
    acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    acceptor.bind(('', int(parameters['listenPort'])))
    acceptor.listen(5)
    cur_thread = threading.current_thread()
    logger.info("Listening to connections on port " + str(parameters['listenPort']) + '\n')

    while True:
        (clientSock, clientAddr) = acceptor.accept()
        print "==== Output Request ====="
        msg = "Connected to " + str(clientAddr[0]) + ":" + str(clientAddr[1])
        logger.info(msg)
        thread3 = threading.Thread(target=sendFile, args=(clientSock, parameters))
        thread3.daemon = True
        thread3.start()
    acceptor.close()
    return 
Example 15
Project: InsightAgent   Author: insightfinder   File: reporting_send.py    License: Apache License 2.0 6 votes vote down vote up
def acceptThread():       
    acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)        
    acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    acceptor.bind(('', int(uploadPort)))
    acceptor.listen(5)
        
    cur_thread=threading.current_thread()
    while True:            
        (clientSock,clientAddr)=acceptor.accept()
        print "====Output Request:"
        msg = "Connected to " + str(clientAddr[0]) + ":" + str(clientAddr[1])
        print msg
        thread3=threading.Thread(target=sendFile(clientSock))
        thread3.daemon=True
        thread3.start()
        #thread3.join()            
    acceptor.close()
    return 
Example 16
Project: facebook-wda   Author: openatx   File: usbmux.py    License: MIT License 6 votes vote down vote up
def __init__(self, addr: Union[str, tuple, socket.socket]):
        """
        Args:
            addr: can be /var/run/usbmuxd or (localhost, 27015)
        """
        self._sock = None
        if isinstance(addr, socket.socket):
            self._sock = addr
            return
        if isinstance(addr, str):
            if not os.path.exists(addr):
                raise MuxError("socket unix:{} unable to connect".format(addr))
            family = socket.AF_UNIX
        else:
            family = socket.AF_INET

        self._sock = socket.socket(family, socket.SOCK_STREAM)
        self._sock.connect(addr) 
Example 17
Project: subtake   Author: kp625544   File: sublist3r.py    License: GNU General Public License v2.0 6 votes vote down vote up
def port_scan(self, host, ports):
        openports = []
        self.lock.acquire()
        for port in ports:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.settimeout(2)
                result = s.connect_ex((host, int(port)))
                if result == 0:
                    openports.append(port)
                s.close()
            except Exception:
                pass
        self.lock.release()
        if len(openports) > 0:
            print("%s%s%s - %sFound open ports:%s %s%s%s" % (G, host, W, R, W, Y, ', '.join(openports), W)) 
Example 18
Project: Paradrop   Author: ParadropLabs   File: pdinstall.py    License: Apache License 2.0 6 votes vote down vote up
def sendCommand(command, data):
    """
    Send a command to the pdinstall service.

    Commands:
    install - Install snaps from a file path or http(s) URL.
        Required data fields:
        sources - List with at least one snap file path or URL.  The snaps
                  are installed in order until one succeeds or all fail.

    Returns True/False for success.  Currently, we cannot check whether the
    call succeeded, only whether it was delived.  A return value of False means
    we could not deliver the command to pdinstall.
    """
    data['command'] = command

    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        sock.connect(SOCKET_ADDRESS)
        sock.send(json.dumps(data))
        return True
    except:
        return False
    finally:
        sock.close() 
Example 19
Project: MicroWebSrv2   Author: jczic   File: XAsyncSockets.py    License: MIT License 6 votes vote down vote up
def Create(asyncSocketsPool, srvAddr, srvBacklog=256, bufSlots=None) :
        try :
            srvSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except :
            raise XAsyncTCPServerException('Create : Cannot open socket (no enought memory).')
        try :
            srvSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            srvSocket.bind(srvAddr)
            srvSocket.listen(srvBacklog)
        except :
            raise XAsyncTCPServerException('Create : Error to binding the TCP server on this address.')
        if not bufSlots :
            bufSlots = XBufferSlots(256, 4096, keepAlloc=True)
        xAsyncTCPServer = XAsyncTCPServer( asyncSocketsPool,
                                           srvSocket,
                                           srvAddr,
                                           bufSlots )
        asyncSocketsPool.NotifyNextReadyForReading(xAsyncTCPServer, True)
        return xAsyncTCPServer

    # ------------------------------------------------------------------------ 
Example 20
Project: EvilOSX   Author: cys3c   File: Server.py    License: GNU General Public License v3.0 6 votes vote down vote up
def start_server(port):
    # Start the server
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(('', port))
    server_socket.listen(128)  # Maximum connections Mac OSX can handle.

    status_messages.append(MESSAGE_INFO + "Successfully started the server on port {0}.".format(str(port)))
    status_messages.append(MESSAGE_INFO + "Waiting for clients...")

    while True:
        client_connection, client_address = ssl.wrap_socket(server_socket, cert_reqs=ssl.CERT_NONE, server_side=True, keyfile="server.key", certfile="server.crt").accept()

        status_messages.append(MESSAGE_INFO + "New client connected!")
        connections.append(client_connection) 
Example 21
Project: oscrypto   Author: wbond   File: _socket_proxy.py    License: MIT License 6 votes vote down vote up
def make_socket_proxy(ip, port, send_callback=None, recv_callback=None):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(('', 8080))
    server.listen(1)
    t = threading.Thread(
        target=listen,
        args=(server, ip, port, send_callback, recv_callback)
    )
    t.start()
    sock = socket.create_connection(('localhost', 8080))
    sock.settimeout(1)
    t.join()
    with _socket_lock:
        data = _sockets[t.ident]
        return (sock, data['lsock'], data['rsock'], server) 
Example 22
Project: jawfish   Author: war-and-code   File: handlers.py    License: MIT License 6 votes vote down vote up
def _connect_unixsocket(self, address):
        use_socktype = self.socktype
        if use_socktype is None:
            use_socktype = socket.SOCK_DGRAM
        self.socket = socket.socket(socket.AF_UNIX, use_socktype)
        try:
            self.socket.connect(address)
            # it worked, so set self.socktype to the used type
            self.socktype = use_socktype
        except socket.error:
            self.socket.close()
            if self.socktype is not None:
                # user didn't specify falling back, so fail
                raise
            use_socktype = socket.SOCK_STREAM
            self.socket = socket.socket(socket.AF_UNIX, use_socktype)
            try:
                self.socket.connect(address)
                # it worked, so set self.socktype to the used type
                self.socktype = use_socktype
            except socket.error:
                self.socket.close()
                raise 
Example 23
Project: Vxscan   Author: al0ne   File: rsync_unauthorized_access.py    License: Apache License 2.0 6 votes vote down vote up
def check(url, ip, ports, apps):
    if verify(vuln, ports, apps):
        try:
            socket.setdefaulttimeout(1.5)
            payload = b"\x40\x52\x53\x59\x4e\x43\x44\x3a\x20\x33\x31\x2e\x30\x0a"
            socket.setdefaulttimeout(timeout)
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_address = (ip, 873)
            sock.connect(server_address)
            sock.sendall(payload)
            initinfo = sock.recv(400)
            if b"RSYNCD" in initinfo:
                sock.sendall(b"\x0a")
            modulelist = sock.recv(200)
            sock.close()
            if len(modulelist) > 0:
                return '873 Rsync Unauthorized Access'
        except Exception as e:
            pass 
Example 24
Project: supervisor-logging   Author: infoxchange   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def main():
    """
    Main application loop.
    """

    env = os.environ

    try:
        host = env['SYSLOG_SERVER']
        port = int(env['SYSLOG_PORT'])
        socktype = socket.SOCK_DGRAM if env['SYSLOG_PROTO'] == 'udp' \
            else socket.SOCK_STREAM
    except KeyError:
        sys.exit("SYSLOG_SERVER, SYSLOG_PORT and SYSLOG_PROTO are required.")

    handler = SysLogHandler(
        address=(host, port),
        socktype=socktype,
    )
    handler.setFormatter(PalletFormatter())

    for event_headers, event_data in supervisor_events(sys.stdin, sys.stdout):
        event = logging.LogRecord(
            name=event_headers['processname'],
            level=logging.INFO,
            pathname=None,
            lineno=0,
            msg=event_data,
            args=(),
            exc_info=None,
        )
        event.process = int(event_headers['pid'])
        handler.handle(event) 
Example 25
Project: svviz   Author: svviz   File: web.py    License: MIT License 5 votes vote down vote up
def getRandomPort():
    import socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(("", 0))
    port = sock.getsockname()[1]
    sock.close()
    return port 
Example 26
Project: svviz   Author: svviz   File: web.py    License: MIT License 5 votes vote down vote up
def checkPortIsClosed(port):
    import socket;
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex(('127.0.0.1', port))
    if result == 0:
       return False
    else:
       return True 
Example 27
Project: cherrypy   Author: cherrypy   File: test_wsgi_unix_socket.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connect(self):
        """
        Override the connect method and assign a unix socket as a transport.
        """
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        sock.connect(self.path)
        self.sock = sock
        atexit.register(lambda: os.remove(self.path)) 
Example 28
Project: iSDX   Author: sdn-ixp   File: logServer.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind((host, port))
        self.listen(5) 
Example 29
Project: iSDX   Author: sdn-ixp   File: client.py    License: Apache License 2.0 5 votes vote down vote up
def send(self, msg):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((self.address, self.port))
        sock.sendall(json.dumps(msg))
        sock.close() 
Example 30
Project: iSDX   Author: sdn-ixp   File: sdnip.py    License: Apache License 2.0 5 votes vote down vote up
def config(self, **kwargs):
        super(BgpRouter, self).config(**kwargs)

        self.cmd('%s/zebra -d -f %s -z %s -i %s'
                 % (BgpRouter.binDir, self.zebraConfFile, self.socket, self.zebraPidFile))
        while True:
            try:
                s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # @UndefinedVariable
                s.connect(self.socket)
                #print 'connected - breaking'
                break
            except Exception, e:
                #print' ERROR: ' + repr(e)
                time.sleep(.1)
        #print 'zebra ready'