我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用errno.ECONNREFUSED。
def test_serialized_with_retry_socket_error_reraised(self): exc = socket.error() exc.errno = errno.ECONNREFUSED plugin = 'glance' fn = 'download_vhd' num_retries = 1 callback = None retry_cb = mock.Mock() with mock.patch.object( self.session, 'call_plugin_serialized', spec=True)\ as call_plugin_serialized: call_plugin_serialized.side_effect = exc self.assertRaises( socket.error, self.session.call_plugin_serialized_with_retry, plugin, fn, num_retries, callback, retry_cb) call_plugin_serialized.assert_called_once_with(plugin, fn) self.assertEqual(0, retry_cb.call_count)
def test_connection_refused(self): cleanup_func, port = refusing_port() self.addCleanup(cleanup_func) with ExpectLog(gen_log, ".*", required=False): self.http_client.fetch("http://127.0.0.1:%d/" % port, self.stop) response = self.wait() self.assertEqual(599, response.code) if sys.platform != 'cygwin': # cygwin returns EPERM instead of ECONNREFUSED here contains_errno = str(errno.ECONNREFUSED) in str(response.error) if not contains_errno and hasattr(errno, "WSAECONNREFUSED"): contains_errno = str(errno.WSAECONNREFUSED) in str(response.error) self.assertTrue(contains_errno, response.error) # This is usually "Connection refused". # On windows, strerror is broken and returns "Unknown error". expected_message = os.strerror(errno.ECONNREFUSED) self.assertTrue(expected_message in str(response.error), response.error)
def test_connection_refused(self): # When a connection is refused, the connect callback should not # be run. (The kqueue IOLoop used to behave differently from the # epoll IOLoop in this respect) cleanup_func, port = refusing_port() self.addCleanup(cleanup_func) stream = IOStream(socket.socket(), self.io_loop) self.connect_called = False def connect_callback(): self.connect_called = True self.stop() stream.set_close_callback(self.stop) # log messages vary by platform and ioloop implementation with ExpectLog(gen_log, ".*", required=False): stream.connect(("127.0.0.1", port), connect_callback) self.wait() self.assertFalse(self.connect_called) self.assertTrue(isinstance(stream.error, socket.error), stream.error) if sys.platform != 'cygwin': _ERRNO_CONNREFUSED = (errno.ECONNREFUSED,) if hasattr(errno, "WSAECONNREFUSED"): _ERRNO_CONNREFUSED += (errno.WSAECONNREFUSED,) # cygwin's errnos don't match those used on native windows python self.assertTrue(stream.error.args[0] in _ERRNO_CONNREFUSED)
def doRead(self): """Called when my socket is ready for reading.""" read = 0 while read < self.maxThroughput: try: data, addr = self.socket.recvfrom(self.maxPacketSize) except socket.error, se: no = se.args[0] if no in (EAGAIN, EINTR, EWOULDBLOCK): return if (no == ECONNREFUSED) or (platformType == "win32" and no == WSAECONNRESET): if self._connectedAddr: self.protocol.connectionRefused() else: raise else: read += len(data) try: self.protocol.datagramReceived(data, addr) except: log.err()
def doRead(self): """Called when my socket is ready for reading.""" read = 0 while read < self.maxThroughput: try: data, addr = self.socket.recvfrom(self.maxPacketSize) read += len(data) self.protocol.datagramReceived(data) except socket.error, se: no = se.args[0] if no in (EAGAIN, EINTR, EWOULDBLOCK): return if (no == ECONNREFUSED) or (platformType == "win32" and no == WSAECONNRESET): self.protocol.connectionRefused() else: raise except: log.deferr()
def _init_mqtt(self): try: logging.info('[Init] Connecting to local broker') if self._mqtt_user is not None and self._mqtt_passwd is not None: self._client.username_pw_set(self._mqtt_user, self._mqtt_passwd) if self._ca_cert is None: self._client.connect(self._mqtt_server, 1883, 60) else: self._client.tls_set(self._ca_cert, cert_reqs=ssl.CERT_REQUIRED) self._client.connect(self._mqtt_server, 8883, 60) self._init_socket_handlers() return False except socket.error, e: if e.errno == errno.ECONNREFUSED: return True raise
def _upcheck(self): """ Check of the API versions. """ try: api = self.supvisors().get_api_version() if api != API_VERSION: self.ctl.output('ERROR: this version of supvisorsctl expects to talk to a server ' 'with API version %s, but the remote version is %s.' % (API_VERSION, api)) return False except xmlrpclib.Fault, e: if e.faultCode == xmlrpc.Faults.UNKNOWN_METHOD: self.ctl.output('ERROR: supervisord responded but did not recognize ' 'the supvisors namespace commands that supvisorsctl uses to control it. ' 'Please check that the [rpcinterface:supervisor] section is enabled ' 'in the configuration file (see sample.conf).') return False raise except socket.error, why: if why.args[0] == errno.ECONNREFUSED: self.ctl.output('ERROR: %s refused connection' % self.ctl.options.serverurl) return False elif why.args[0] == errno.ENOENT: self.ctl.output('ERROR: %s no such file' % self.ctl.options.serverurl) return False raise return True
def check_available_service(self, host): list_available_port = [] list_common_port = [21,22,23,25,53,80,110,111,135,139,143,443,445,993,995,1723,3306,3389,5900,8080] for port in list_common_port: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((host, port)) if port == 80: data = url_req.header_info("http://" + host, "") log.console_log("Found HTPP Service : ({} OPEN)".format(str(port)) ) log.console_log("\n{}".format(data)) elif port == 443: data = url_req.header_info("https://" + host, "") else: print("port :" + str(port) + " OPEN! " + s.recv(4096)) except socket.error as e: if e.errno == errno.ECONNREFUSED or e.errno == 113: pass else: print("port :" + str(port) + str(e) + "closed") s.close()
def test_connection_refused(self): # When a connection is refused, the connect callback should not # be run. (The kqueue IOLoop used to behave differently from the # epoll IOLoop in this respect) cleanup_func, port = refusing_port() self.addCleanup(cleanup_func) stream = MicroProxyIOStream(socket.socket(), io_loop=self.io_loop) self.connect_called = False def connect_callback(): self.connect_called = True self.stop() stream.set_close_callback(self.stop) stream.connect(("127.0.0.1", port), connect_callback) self.wait() self.assertFalse(self.connect_called) self.assertTrue(isinstance(stream.error, socket.error), stream.error) if sys.platform != 'cygwin': _ERRNO_CONNREFUSED = (errno.ECONNREFUSED,) if hasattr(errno, "WSAECONNREFUSED"): _ERRNO_CONNREFUSED += (errno.WSAECONNREFUSED,) # cygwin's errnos don't match those used on native windows python self.assertTrue(stream.error.args[0] in _ERRNO_CONNREFUSED)
def test_connect_ex_error(self): with support.transient_internet(REMOTE_HOST): s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, ca_certs=REMOTE_ROOT_CERT) try: rc = s.connect_ex((REMOTE_HOST, 444)) # Issue #19919: Windows machines or VMs hosted on Windows # machines sometimes return EWOULDBLOCK. errors = ( errno.ECONNREFUSED, errno.EHOSTUNREACH, errno.ETIMEDOUT, errno.EWOULDBLOCK, ) self.assertIn(rc, errors) finally: s.close()
def listen(self): res0 = self._resolveAddr() for res in res0: if res[0] is socket.AF_INET6 or res is res0[-1]: break # We need remove the old unix socket if the file exists and # nobody is listening on it. if self._unix_socket: tmp = socket.socket(res[0], res[1]) try: tmp.connect(res[4]) except socket.error, err: eno, message = err.args if eno == errno.ECONNREFUSED: os.unlink(res[4]) self.handle = socket.socket(res[0], res[1]) self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(self.handle, 'settimeout'): self.handle.settimeout(None) self.handle.bind(res[4]) self.handle.listen(128)
def send_syntax_request(file, operation): try: syntaxerPort = int(os.environ.get( 'CSSCRIPT_SYNTAXER_PORT', 'not_configured')) if syntaxerPort == 'not_configured': return None clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientsocket.connect(('localhost', syntaxerPort)) request = '-client:{0}\n-op:{1}\n-script:{2}'.format( os.getpid(), operation, file) clientsocket.send(request.encode('utf-8')) response = clientsocket.recv(1024 * 5) return response.decode('utf-8') except socket_error as serr: if serr.errno == errno.ECONNREFUSED: print(serr) # -----------------
def pcl_can_query_retry(e): """ ???????? ?????????? ??? ?????? pcl_query_retry ?? ??????????? ?????????? ??????? ?????????: e (Exception) -- ?????????? ?? pcl_query_retry ?????????: None ??? ?????????????? ?????????? """ if type(e) == pclError: # https://docs.pcloud.com/errors/index.html if e.errno >= 3000: pass # HTTP elif (e.errno >= 500 and e.errno < 600) or e.errno == 401 or e.errno == 429: pass else: raise e elif type(e) == socket.error and not (e.errno == errno.ECONNRESET or e.errno == errno.ECONNREFUSED): raise e
def pingServer(host, port, timeout): """ The function tries to ping (sends STATUS command) to the NG/AMS Server running on the given host using the given port number. """ logger.debug("Pinging NG/AMS Server: %s:%d. Timeout: %.3f [s]", host, port, timeout) startTime = time.time() while True: try: resp = ngamsHttpUtils.httpGet(host, port, NGAMS_STATUS_CMD) with contextlib.closing(resp): if resp.status in (NGAMS_HTTP_SUCCESS, NGAMS_HTTP_UNAUTH): logger.debug("Successfully pinged NG/AMS Server") return except socket.error as e: if e.errno != errno.ECONNREFUSED: raise if (time.time() - startTime) >= timeout: break time.sleep(0.2) errMsg = "NGAS Server running on %s:%d did not respond within %.3f [s]" raise Exception(errMsg % (host, port, timeout))
def connectThread(self): while not self.connected: try: self.client.connect((HOST, PORT)) except socket.error as e: pass finally: if e.errno == errno.EINPROGRESS: time.sleep(1.0) elif e.errno == errno.ECONNREFUSED: time.sleep(1.0) elif e.errno == errno.EALREADY: time.sleep(1.0) elif e.errno == errno.EINVAL: break elif e.errno == errno.EISCONN: logger.log("[button]: Connected to Artoo.") self.connected = True self.buttonsInitialized = False else: logger.log("[button]: Unexpected socket exception: %s" % e) time.sleep(1.0)
def test_connection_refused(self): server_socket, port = bind_unused_port() server_socket.close() with ExpectLog(gen_log, ".*", required=False): self.http_client.fetch("http://localhost:%d/" % port, self.stop) response = self.wait() self.assertEqual(599, response.code) if sys.platform != 'cygwin': # cygwin returns EPERM instead of ECONNREFUSED here self.assertTrue(str(errno.ECONNREFUSED) in str(response.error), response.error) # This is usually "Connection refused". # On windows, strerror is broken and returns "Unknown error". expected_message = os.strerror(errno.ECONNREFUSED) self.assertTrue(expected_message in str(response.error), response.error)
def test_connection_refused(self): # When a connection is refused, the connect callback should not # be run. (The kqueue IOLoop used to behave differently from the # epoll IOLoop in this respect) server_socket, port = bind_unused_port() server_socket.close() stream = IOStream(socket.socket(), self.io_loop) self.connect_called = False def connect_callback(): self.connect_called = True stream.set_close_callback(self.stop) # log messages vary by platform and ioloop implementation with ExpectLog(gen_log, ".*", required=False): stream.connect(("localhost", port), connect_callback) self.wait() self.assertFalse(self.connect_called) self.assertTrue(isinstance(stream.error, socket.error), stream.error) if sys.platform != 'cygwin': # cygwin's errnos don't match those used on native windows python self.assertEqual(stream.error.args[0], errno.ECONNREFUSED)
def _conn_request(self, conn, request_uri, method, body, headers): for i in range(2): try: conn.request(method, request_uri, body, headers) except socket.gaierror: conn.close() raise ServerNotFoundError("Unable to find the server at %s" % conn.host) except socket.error, e: if not hasattr(e, 'errno'): # I don't know what this is so lets raise it if it happens raise elif e.errno == errno.ECONNREFUSED: # Connection refused raise # Just because the server closed the connection doesn't apparently mean # that the server didn't send a response. pass except httplib.HTTPException: # Just because the server closed the connection doesn't apparently mean # that the server didn't send a response. pass try: response = conn.getresponse() except (socket.error, httplib.HTTPException): if i == 0: conn.close() conn.connect() continue else: raise else: content = "" if method == "HEAD": response.close() else: content = response.read() response = Response(response) if method != "HEAD": content = _decompressContent(response, content) break return (response, content)
def test_connection_refused(self): server_socket, port = bind_unused_port() server_socket.close() with ExpectLog(gen_log, ".*"): self.http_client.fetch("http://localhost:%d/" % port, self.stop) response = self.wait() self.assertEqual(599, response.code) if sys.platform != 'cygwin': # cygwin returns EPERM instead of ECONNREFUSED here self.assertTrue(str(errno.ECONNREFUSED) in str(response.error), response.error) # This is usually "Connection refused". # On windows, strerror is broken and returns "Unknown error". expected_message = os.strerror(errno.ECONNREFUSED) self.assertTrue(expected_message in str(response.error), response.error)
def test_listen(self): logger = self.useFixture(FakeLogger(format="%(asctime)s %(message)s")) self.executable.listen(6666) self.executable.sleep(1) self.executable.spawn() # Try to connect to the socket sock = socket.socket() transient = (errno.ECONNREFUSED, errno.ECONNRESET) attempts = 10 for i in range(1, attempts + 1): try: sock.connect(("127.0.0.1", self.executable.port)) except socket.error as error: # pragma: no cover if error.errno in transient and i != attempts: time.sleep(0.05 * i) continue logging.error("connection attempt %d failed", i) raise error break self.assertEqual("127.0.0.1", sock.getsockname()[0])
def connectionTest(ipAddress, port): s = socket.socket() s.settimeout(CONNECTION_WAIT_TIME) try: s.connect((ipAddress, port)) s.close() return STATUS.CONNECTED except socket.timeout, exc: return STATUS.TIMEOUT except socket.gaierror, exc: return STATUS.TIMEOUT except socket.error, exc: if exc.errno != errno.ECONNREFUSED: return STATUS.TIMEOUT else: return STATUS.REFUSED
def doRead(self): """ Called when my socket is ready for reading. """ read = 0 while read < self.maxThroughput: try: data, addr = self.socket.recvfrom(self.maxPacketSize) read += len(data) self.protocol.datagramReceived(data) except socket.error as se: no = se.args[0] if no in (EAGAIN, EINTR, EWOULDBLOCK): return if no == ECONNREFUSED: self.protocol.connectionRefused() else: raise except: log.deferr()
def write(self, data): """ Write a datagram. """ try: return self.socket.send(data) except socket.error as se: no = se.args[0] if no == EINTR: return self.write(data) elif no == EMSGSIZE: raise error.MessageLengthError("message too long") elif no == ECONNREFUSED: self.protocol.connectionRefused() elif no == EAGAIN: # oh, well, drop the data. The only difference from UDP # is that UDP won't ever notice. # TODO: add TCP-like buffering pass else: raise
def _get_connection(self): connection = None logger.info("Connecting...") for i in range(self.timeout): try: if not connection: logger.debug("Connecting. Timeout in {:d} seconds.".format(self.timeout - i)) connection = rpyc.classic.connect('localhost', self.port) else: logger.debug("Found connection, testing. Timeout in {:d} seconds.".format(self.timeout - i)) connection.ping(timeout=1) logger.debug("Connection ok, returning.") logger.info("Connected.") return connection except (socket.error, rpyc.core.protocol.PingError, rpyc.core.async.AsyncResultTimeout) as e: if e is socket.error and not e.errno == errno.ECONNREFUSED: raise if i == self.timeout - 1: raise elif e is socket.error: sleep(1)
def test_025_accept_errors(self): debug.hub_exceptions(True) listener = greensocket.socket() listener.bind(('localhost', 0)) # NOT calling listen, to trigger the error with capture_stderr() as log: self.spawn_server(sock=listener) eventlet.sleep(0) # need to enter server loop try: eventlet.connect(self.server_addr) self.fail("Didn't expect to connect") except socket.error as exc: self.assertEqual(support.get_errno(exc), errno.ECONNREFUSED) log_content = log.getvalue() assert 'Invalid argument' in log_content, log_content debug.hub_exceptions(False)
def _get_ip(self): if self._ex_ip: return self._ex_ip s = socket.socket() if ':' in self.tracker: domain, port_str = self.tracker.split(':') tracker_tuple = (domain, int(port_str)) else: tracker_tuple = (self.tracker, 80) try: s.connect(tracker_tuple) except socket.error as e: if e.errno == errno.ECONNREFUSED or e.errno == errno.ETIMEDOUT: raise TrackerUnavailable else: raise self._ex_ip = s.getsockname()[0] return self._ex_ip
def _init_sock(self): if self.unix_socket: # try remove the sock file it already exists _sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) try: _sock.connect(self.unix_socket) except (socket.error, OSError) as err: if err.args[0] == errno.ECONNREFUSED: os.unlink(self.unix_socket) else: _sock = socket.socket(self.socket_family, socket.SOCK_STREAM) _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, "SO_REUSEPORT"): try: _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) except socket.error as err: if err[0] in (errno.ENOPROTOOPT, errno.EINVAL): pass else: raise _sock.settimeout(None) self.sock = _sock
def test_serialized_with_retry_socket_error_reraised(self): exc = socket.error() exc.errno = errno.ECONNREFUSED plugin = 'glance' fn = 'download_vhd' num_retries = 1 callback = None retry_cb = mock.Mock() with mock.patch.object(self.session, 'call_plugin_serialized', spec=True) as call_plugin_serialized: call_plugin_serialized.side_effect = exc self.assertRaises(socket.error, self.session.call_plugin_serialized_with_retry, plugin, fn, num_retries, callback, retry_cb) call_plugin_serialized.assert_called_once_with(plugin, fn) self.assertEqual(0, retry_cb.call_count)