Python socket.create_connection() Examples
The following are 30
code examples of socket.create_connection().
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: SockPuppet.py From ALF with Apache License 2.0 | 8 votes |
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 #2
Source File: socks.py From vulscan with MIT License | 7 votes |
def create_connection(dest_pair, proxy_type=None, proxy_addr=None, proxy_port=None, proxy_rdns=True, proxy_username=None, proxy_password=None, timeout=None, source_address=None): """create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object Like socket.create_connection(), but connects to proxy before returning the socket object. dest_pair - 2-tuple of (IP/hostname, port). **proxy_args - Same args passed to socksocket.set_proxy() if present. timeout - Optional socket timeout value, in seconds. source_address - tuple (host, port) for the socket to bind to as its source address before connecting (only for compatibility) """ sock = socksocket() if isinstance(timeout, (int, float)): sock.settimeout(timeout) if proxy_type is not None: sock.set_proxy(proxy_type, proxy_addr, proxy_port, proxy_rdns, proxy_username, proxy_password) sock.connect(dest_pair) return sock
Example #3
Source File: test.py From px with MIT License | 7 votes |
def checkPxStart(ip, port): # Make sure Px starts retry = 20 while True: try: socket.create_connection((ip, port), 2) break except (socket.timeout, ConnectionRefusedError): time.sleep(1) retry -= 1 if retry == 0: print("Px didn't start @ %s:%d" % (ip, port)) return False return True # Test --listen and --port, --hostonly, --gateway and --allow
Example #4
Source File: socks.py From plugin.video.kmediatorrent with GNU General Public License v3.0 | 7 votes |
def create_connection(dest_pair, proxy_type=None, proxy_addr=None, proxy_port=None, proxy_username=None, proxy_password=None, timeout=None): """create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object Like socket.create_connection(), but connects to proxy before returning the socket object. dest_pair - 2-tuple of (IP/hostname, port). **proxy_args - Same args passed to socksocket.set_proxy(). timeout - Optional socket timeout value, in seconds. """ sock = socksocket() if isinstance(timeout, (int, float)): sock.settimeout(timeout) sock.set_proxy(proxy_type, proxy_addr, proxy_port, proxy_username, proxy_password) sock.connect(dest_pair) return sock
Example #5
Source File: ssl_support.py From pledgeservice with Apache License 2.0 | 6 votes |
def connect(self): sock = socket.create_connection( (self.host, self.port), getattr(self, 'source_address', None) ) # Handle the socket if a (proxy) tunnel is present if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None): self.sock = sock self._tunnel() self.sock = ssl.wrap_socket( sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle ) try: match_hostname(self.sock.getpeercert(), self.host) except CertificateError: self.sock.shutdown(socket.SHUT_RDWR) self.sock.close() raise
Example #6
Source File: ssl.py From ironpython2 with Apache License 2.0 | 6 votes |
def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None): """Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt.""" host, port = addr if ca_certs is not None: cert_reqs = CERT_REQUIRED else: cert_reqs = CERT_NONE context = _create_stdlib_context(ssl_version, cert_reqs=cert_reqs, cafile=ca_certs) with closing(create_connection(addr)) as sock: with closing(context.wrap_socket(sock)) as sslsock: dercert = sslsock.getpeercert(True) return DER_cert_to_PEM_cert(dercert)
Example #7
Source File: transfer.py From Windows-Agent with Apache License 2.0 | 6 votes |
def insure_conn(self): """ insure tcp connection is alive, if not alive or client is None create a new tcp connection. Args: addr (JSONClient): client which can send rpc request Returns: JSONClient with given addr """ for _ in range(3): try: self.call('Transfer.Ping', None) except Exception as e: logging.error(e) logging.error("lose connection to transfer, prepare to rebuild") self.socket = socket.create_connection(self.addr) break
Example #8
Source File: test_connection.py From ServerlessCrawler-VancouverRealState with MIT License | 6 votes |
def test_defer_connect(self): import socket for db in self.databases: d = db.copy() try: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(d['unix_socket']) except KeyError: sock = socket.create_connection( (d.get('host', 'localhost'), d.get('port', 3306))) for k in ['unix_socket', 'host', 'port']: try: del d[k] except KeyError: pass c = pymysql.connect(defer_connect=True, **d) self.assertFalse(c.open) c.connect(sock) c.close() sock.close()
Example #9
Source File: ftplib.py From ironpython2 with Apache License 2.0 | 6 votes |
def connect(self, host='', port=0, timeout=-999): '''Connect to host. Arguments are: - host: hostname to connect to (string, default previous host) - port: port to connect to (integer, default previous port) ''' if host != '': self.host = host if port > 0: self.port = port if timeout != -999: self.timeout = timeout self.sock = socket.create_connection((self.host, self.port), self.timeout) self.af = self.sock.family self.file = self.sock.makefile('rb') self.welcome = self.getresp() return self.welcome
Example #10
Source File: xinling.py From cc98 with MIT License | 6 votes |
def function_hook_parameter(oldfunc, parameter_index, parameter_name, parameter_value): """ 这个函数只是用于辅助实现多IP爬取,并不是很重要,你可以放心地跳过此函数继续阅读 创造一个wrapper函数,劫持oldfunc传入的第parameter_index名为parameter_name的函数,固定其值为parameter_value; 不影响调用该函数时传入的任何其他参数 用法: 原函数 = function_hook_parameter(原函数, 从1开始计数的参数所处的位置, 这个参数的名称, 需要替换成的参数值) 例子: 需要劫持socket.create_connection这个函数,其函数原型如下: create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None) 需要对其第3个参数source_address固定为value,劫持方法如下 socket.create_connection = function_hook_parameter(socket.create_connection, 3, "source_address", value) """ real_func = oldfunc def newfunc(*args, **kwargs): # args是参数列表list,kwargs是带有名称keyword的参数dict newargs = list(args) if len(args) >= parameter_index: # 如果这个参数被直接传入,那么肯定其前面的参数都是无名称的参数,args的长度肯定长于其所在的位置 newargs[parameter_index - 1] = parameter_value # 第3个参数在list的下表是2 else: # 如果不是直接传入,那么就在kwargs中 或者可选参数不存在这个参数,强制更新掉kwargs即可 kwargs[parameter_name] = parameter_value return real_func(*newargs, **kwargs) return newfunc
Example #11
Source File: misc.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None): """Backport of 3-argument create_connection() for Py2.6. Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default. """ host, port = address err = None for res in getaddrinfo(host, port, 0, SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket(af, socktype, proto) if timeout is not _GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(timeout) if source_address: sock.bind(source_address) sock.connect(sa) return sock except error as _: err = _ if sock is not None: sock.close() if err is not None: raise err else: raise error("getaddrinfo returns an empty list") # Backport from Py2.7 for Py2.6:
Example #12
Source File: test_custodia.py From custodia with GNU General Public License v3.0 | 6 votes |
def check_socket(self): url = urlparse(self.socket_url) timeout = 0.5 if url.scheme == 'http+unix': address = unquote(url.netloc) s = socket.socket(socket.AF_UNIX) s.settimeout(timeout) try: s.connect(address) except OSError as e: self.fail("Server socket unavailable: {}".format(e)) finally: s.close() else: host, port = url.netloc.rsplit(":", 1) try: socket.create_connection( (host, int(port)), timeout=timeout ).close() except OSError as e: self.fail("Server socket unavailable: {}".format(e))
Example #13
Source File: _socket_proxy.py From oscrypto with MIT License | 6 votes |
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 #14
Source File: test_ssl.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_recv_zero(self): server = ThreadedEchoServer(CERTFILE) server.__enter__() self.addCleanup(server.__exit__, None, None) s = socket.create_connection((HOST, server.port)) self.addCleanup(s.close) s = ssl.wrap_socket(s, suppress_ragged_eofs=False) self.addCleanup(s.close) # recv/read(0) should return no data s.send(b"data") self.assertEqual(s.recv(0), b"") self.assertEqual(s.read(0), b"") self.assertEqual(s.read(), b"data") # Should not block if the other end sends no data s.setblocking(False) self.assertEqual(s.recv(0), b"") self.assertEqual(s.recv_into(bytearray()), 0)
Example #15
Source File: transport.py From smbprotocol with MIT License | 6 votes |
def socket_connect(func): def wrapped(self, *args, **kwargs): if not self._connected: log.info("Connecting to DirectTcp socket") try: self._sock = socket.create_connection((self.server, self.port), timeout=self.timeout) except (OSError, socket.gaierror) as err: raise ValueError("Failed to connect to '%s:%s': %s" % (self.server, self.port, str(err))) self._sock.settimeout(None) # Make sure the socket is in blocking mode. self._t_recv = threading.Thread(target=self.recv_thread, name="recv-%s:%s" % (self.server, self.port)) self._t_recv.daemon = True self._t_recv.start() self._connected = True func(self, *args, **kwargs) return wrapped
Example #16
Source File: connection.py From pledgeservice with Apache License 2.0 | 5 votes |
def _new_conn(self): """ Establish a socket connection and set nodelay settings on it. :return: a new socket connection """ extra_args = [] if self.source_address: # Python 2.7+ extra_args.append(self.source_address) conn = socket.create_connection( (self.host, self.port), self.timeout, *extra_args) conn.setsockopt( socket.IPPROTO_TCP, socket.TCP_NODELAY, self.tcp_nodelay) return conn
Example #17
Source File: ProxiesFunctions.py From MultiProxies with GNU General Public License v3.0 | 5 votes |
def unsetProxy(): socket.socket = _orgsocket socket.create_connection = _orgcreateconnection socket.getaddrinfo = _orggetaddrinfo ######################################################################################### ##Client Globals
Example #18
Source File: ProxiesFunctions.py From MultiProxies with GNU General Public License v3.0 | 5 votes |
def setProxy(scheme, ip, port): """ reference : https://pypi.python.org/pypi/GoogleScraper/0.0.2.dev1 @scraping.py line:311 + getaddrinfo function. modified by DM_ @param scheme: socks4,socks5 @param ip: ip @param port: port. """ def create_connection(address, timeout=None, source_address=None): sock = socks.socksocket() sock.connect(address) return sock def getaddrinfo(*args): return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))] pmapping = { 'socks4': 1, 'socks5': 2, 'http': 3 } # Patch the socket module # rdns is by default on true. Never use rnds=False with TOR, otherwise you are screwed! socks.setdefaultproxy(pmapping.get(scheme), ip, port, rdns=True) socks.wrapmodule(socket) socket.socket = socks.socksocket ##add for socket. if not then can only use requests or other modules but socket. socket.create_connection = create_connection socket.getaddrinfo = getaddrinfo
Example #19
Source File: ssl_support.py From ironpython2 with Apache License 2.0 | 5 votes |
def connect(self): sock = socket.create_connection( (self.host, self.port), getattr(self, 'source_address', None) ) # Handle the socket if a (proxy) tunnel is present if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None): self.sock = sock self._tunnel() # http://bugs.python.org/issue7776: Python>=3.4.1 and >=2.7.7 # change self.host to mean the proxy server host when tunneling is # being used. Adapt, since we are interested in the destination # host for the match_hostname() comparison. actual_host = self._tunnel_host else: actual_host = self.host if hasattr(ssl, 'create_default_context'): ctx = ssl.create_default_context(cafile=self.ca_bundle) self.sock = ctx.wrap_socket(sock, server_hostname=actual_host) else: # This is for python < 2.7.9 and < 3.4? self.sock = ssl.wrap_socket( sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle ) try: match_hostname(self.sock.getpeercert(), actual_host) except CertificateError: self.sock.shutdown(socket.SHUT_RDWR) self.sock.close() raise
Example #20
Source File: test_socket.py From ironpython2 with Apache License 2.0 | 5 votes |
def _testFamily(self): self.cli = socket.create_connection((HOST, self.port), timeout=30) self.addCleanup(self.cli.close) self.assertEqual(self.cli.family, 2)
Example #21
Source File: test_socket.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_create_connection_timeout(self): # Issue #9792: create_connection() should not recast timeout errors # as generic socket errors. with self.mocked_socket_module(): with self.assertRaises(socket.timeout): socket.create_connection((HOST, 1234))
Example #22
Source File: test_socket.py From ironpython2 with Apache License 2.0 | 5 votes |
def clientSetUp(self): # We're inherited below by BasicTCPTest2, which also inherits # BasicTCPTest, which defines self.port referenced below. self.cli = socket.create_connection((HOST, self.port)) self.serv_conn = self.cli
Example #23
Source File: poplib.py From ironpython2 with Apache License 2.0 | 5 votes |
def __init__(self, host, port=POP3_PORT, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): self.host = host self.port = port self.sock = socket.create_connection((host, port), timeout) self.file = self.sock.makefile('rb') self._debugging = 0 self.welcome = self._getresp()
Example #24
Source File: test_socket.py From ironpython2 with Apache License 2.0 | 5 votes |
def _testInsideTimeout(self): self.cli = sock = socket.create_connection((HOST, self.port)) data = sock.recv(5) self.assertEqual(data, "done!")
Example #25
Source File: smtplib.py From ironpython2 with Apache License 2.0 | 5 votes |
def _get_socket(self, host, port, timeout): if self.debuglevel > 0: print>>stderr, 'connect:', (host, port) new_socket = socket.create_connection((host, port), timeout) new_socket = ssl.wrap_socket(new_socket, self.keyfile, self.certfile) self.file = SSLFakeFile(new_socket) return new_socket
Example #26
Source File: connection.py From pledgeservice with Apache License 2.0 | 5 votes |
def _new_conn(self): """ Establish a socket connection and set nodelay settings on it. :return: a new socket connection """ extra_args = [] if self.source_address: # Python 2.7+ extra_args.append(self.source_address) conn = socket.create_connection( (self.host, self.port), self.timeout, *extra_args) conn.setsockopt( socket.IPPROTO_TCP, socket.TCP_NODELAY, self.tcp_nodelay) return conn
Example #27
Source File: ssl_support.py From lambda-packs with MIT License | 5 votes |
def connect(self): sock = socket.create_connection( (self.host, self.port), getattr(self, 'source_address', None) ) # Handle the socket if a (proxy) tunnel is present if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None): self.sock = sock self._tunnel() # http://bugs.python.org/issue7776: Python>=3.4.1 and >=2.7.7 # change self.host to mean the proxy server host when tunneling is # being used. Adapt, since we are interested in the destination # host for the match_hostname() comparison. actual_host = self._tunnel_host else: actual_host = self.host if hasattr(ssl, 'create_default_context'): ctx = ssl.create_default_context(cafile=self.ca_bundle) self.sock = ctx.wrap_socket(sock, server_hostname=actual_host) else: # This is for python < 2.7.9 and < 3.4? self.sock = ssl.wrap_socket( sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle ) try: match_hostname(self.sock.getpeercert(), actual_host) except CertificateError: self.sock.shutdown(socket.SHUT_RDWR) self.sock.close() raise
Example #28
Source File: imaplib.py From ironpython2 with Apache License 2.0 | 5 votes |
def open(self, host = '', port = IMAP4_PORT): """Setup connection to remote server on "host:port" (default: localhost:standard IMAP4 port). This connection will be used by the routines: read, readline, send, shutdown. """ self.host = host self.port = port self.sock = socket.create_connection((host, port)) self.file = self.sock.makefile('rb')
Example #29
Source File: telnetlib.py From ironpython2 with Apache License 2.0 | 5 votes |
def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): """Connect to a host. The optional second argument is the port number, which defaults to the standard telnet port (23). Don't try to reopen an already connected instance. """ self.eof = 0 if not port: port = TELNET_PORT self.host = host self.port = port self.timeout = timeout self.sock = socket.create_connection((host, port), timeout)
Example #30
Source File: imaplib.py From ironpython2 with Apache License 2.0 | 5 votes |
def open(self, host = '', port = IMAP4_SSL_PORT): """Setup connection to remote server on "host:port". (default: localhost:standard IMAP4 SSL port). This connection will be used by the routines: read, readline, send, shutdown. """ self.host = host self.port = port self.sock = socket.create_connection((host, port)) self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile) self.file = self.sslobj.makefile('rb')