當前位置: 首頁>>代碼示例>>Python>>正文


Python socket.gaierror方法代碼示例

本文整理匯總了Python中socket.gaierror方法的典型用法代碼示例。如果您正苦於以下問題:Python socket.gaierror方法的具體用法?Python socket.gaierror怎麽用?Python socket.gaierror使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在socket的用法示例。


在下文中一共展示了socket.gaierror方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: socket_connect

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import gaierror [as 別名]
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 
開發者ID:jborean93,項目名稱:smbprotocol,代碼行數:20,代碼來源:transport.py

示例2: _do_dns_lookup

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import gaierror [as 別名]
def _do_dns_lookup(hostname: str, port: int) -> str:
    try:
        addr_infos = socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.IPPROTO_IP)
    except (socket.gaierror, IndexError, ConnectionError):
        raise ServerHostnameCouldNotBeResolved(f"Could not resolve {hostname}")

    family, socktype, proto, canonname, sockaddr = addr_infos[0]

    # By default use the first DNS entry, IPv4 or IPv6
    tentative_ip_addr = sockaddr[0]

    # But try to use IPv4 if we have both IPv4 and IPv6 addresses, to work around buggy networks
    for family, socktype, proto, canonname, sockaddr in addr_infos:
        if family == socket.AF_INET:
            tentative_ip_addr = sockaddr[0]

    return tentative_ip_addr 
開發者ID:nabla-c0d3,項目名稱:sslyze,代碼行數:19,代碼來源:server_setting.py

示例3: is_valid_ip

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import gaierror [as 別名]
def is_valid_ip(ip):
    """Returns true if the given string is a well-formed IP address.

    Supports IPv4 and IPv6.
    """
    if not ip or '\x00' in ip:
        # getaddrinfo resolves empty strings to localhost, and truncates
        # on zero bytes.
        return False
    try:
        res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,
                                 socket.SOCK_STREAM,
                                 0, socket.AI_NUMERICHOST)
        return bool(res)
    except socket.gaierror as e:
        if e.args[0] == socket.EAI_NONAME:
            return False
        raise
    return True 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:21,代碼來源:netutil.py

示例4: test_ipv6

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import gaierror [as 別名]
def test_ipv6(self):
        try:
            [sock] = bind_sockets(None, '::1', family=socket.AF_INET6)
            port = sock.getsockname()[1]
            self.http_server.add_socket(sock)
        except socket.gaierror as e:
            if e.args[0] == socket.EAI_ADDRFAMILY:
                # python supports ipv6, but it's not configured on the network
                # interface, so skip this test.
                return
            raise
        url = '%s://[::1]:%d/hello' % (self.get_protocol(), port)

        # ipv6 is currently enabled by default but can be disabled
        self.http_client.fetch(url, self.stop, allow_ipv6=False)
        response = self.wait()
        self.assertEqual(response.code, 599)

        self.http_client.fetch(url, self.stop)
        response = self.wait()
        self.assertEqual(response.body, b"Hello world!") 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:23,代碼來源:simple_httpclient_test.py

示例5: get_host_ip

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import gaierror [as 別名]
def get_host_ip(hostIP=None):
    if hostIP is None or hostIP == 'auto':
        hostIP = 'ip'

    if hostIP == 'dns':
        hostIP = socket.getfqdn()
    elif hostIP == 'ip':
        from socket import gaierror
        try:
            hostIP = socket.gethostbyname(socket.getfqdn())
        except gaierror:
            logger.warn('gethostbyname(socket.getfqdn()) failed... trying on hostname()')
            hostIP = socket.gethostbyname(socket.gethostname())
        if hostIP.startswith("127."):
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            # doesn't have to be reachable
            s.connect(('10.255.255.255', 1))
            hostIP = s.getsockname()[0]
    return hostIP 
開發者ID:aws,項目名稱:sagemaker-xgboost-container,代碼行數:21,代碼來源:tracker.py

示例6: tunnel_traffic

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import gaierror [as 別名]
def tunnel_traffic(self):
        "Tunnel traffic to remote host:port"
        logger.info("%03d " % self.reqNum + Fore.CYAN + '[D] SSL Pass-Thru: https://%s/' % self.path)
        server_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            server_conn.connect((self.host, int(self.port)))
            self.wfile.write(("HTTP/1.1 200 Connection established\r\n" +
                              "Proxy-agent: %s\r\n" % self.version_string() +
                              "\r\n").encode('ascii'))
            read_write(self.connection, server_conn)
        except TimeoutError:
            self.wfile.write(b"HTTP/1.1 504 Gateway Timeout\r\n\r\n")
            logger.warning("%03d " % self.reqNum + Fore.YELLOW + 'Timed Out: https://%s:%s/' % (self.host, self.port))
        except socket.gaierror as e:
            self.wfile.write(b"HTTP/1.1 503 Service Unavailable\r\n\r\n")
            logger.warning("%03d " % self.reqNum + Fore.YELLOW + '%s: https://%s:%s/' % (e, self.host, self.port))
        finally:
            # We don't maintain a connection reuse pool, so close the connection anyway
            server_conn.close() 
開發者ID:wheever,項目名稱:ProxHTTPSProxyMII,代碼行數:21,代碼來源:ProxyTool.py

示例7: select_address_family

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import gaierror [as 別名]
def select_address_family(host, port):
    """Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on
    the host and port."""
    # 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 host.startswith("unix://"):
        return socket.AF_UNIX
    elif ":" in host and hasattr(socket, "AF_INET6"):
        return socket.AF_INET6
    return socket.AF_INET 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:22,代碼來源:serving.py

示例8: select_ip_version

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import gaierror [as 別名]
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 
開發者ID:jpush,項目名稱:jbox,代碼行數:19,代碼來源:serving.py

示例9: main

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import gaierror [as 別名]
def main():
    try:
        f = ftplib.FTP(HOST)
    except (socket.error, socket.gaierror) as e:
        print('ERROR: 無法連接 "{}"'.format(HOST))
        return
    print('*** 已連接到 "{}"'.format(HOST))

    try:
        f.login()
    except ftplib.error_perm:
        print('ERROR: 無法匿名登錄')
        f.quit()
        return
    print('*** 已匿名身份登錄')

    try:
        f.cwd(DIRN)
    except ftplib.error_perm:
        print('ERROR: 無法跳轉到 "{}" 目錄'.format(DIRN))
        f.quit()
        return
    print('*** 跳轉到 "{}" 目錄'.format(DIRN))

    try:
        f.retrbinary('RETR %s' % FILE, open(FILE, 'wb').write)
    except ftplib.error_perm:
        print('ERROR: 無法讀取文件 "{}"'.format(FILE))
        os.unlink(FILE)
    else:
        print('*** 已下載 "{}" 到當前目錄'.format(FILE))
    f.quit() 
開發者ID:wdxtub,項目名稱:deep-learning-note,代碼行數:34,代碼來源:1_ftp_client.py

示例10: scan

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import gaierror [as 別名]
def scan(port):
		s = socket.socket()
		
		try:
			result = s.connect_ex((host,port))
		except socket.gaierror as e:
			if args.verbose == True:
				print "[" + t.red("!") + "]Critical. A GAIerror was raised with the following error message."
				print e 
				sys.exit(0)
			else:
				print "[" + t.red("!") + "]Critical. An error was raised while attempting to connect."
				sys.exit(0)
			
		if args.verbose == True:
			print "\n[" + t.green("+") + "]working on port: " + str(port)
			time.sleep(0.250)      
	
		if result == 0:
			counting_open.append(port)
			if args.verbose == True:
				print "\n[" + t.magenta("~") + "]" + str(port) + " -> open." 
				time.sleep(0.250)
			s.close()
		else:
			counting_close.append(port)
			if args.verbose == True:
				print "\n[" + t.magenta("~") + "]" + str(port) + " -> closed." 
				time.sleep(0.250)
			s.close() 
開發者ID:NullArray,項目名稱:QuickScan,代碼行數:32,代碼來源:quickscan.py

示例11: _xmit_packet

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import gaierror [as 別名]
def _xmit_packet(self, retry=True, delay_xmit=None):
        if self.sequencenumber:
            self.sequencenumber += 1
        if delay_xmit is not None:
            # skip transmit, let retry timer do it's thing
            self.waiting_sessions[self] = {}
            self.waiting_sessions[self]['ipmisession'] = self
            self.waiting_sessions[self]['timeout'] = delay_xmit +  _monotonic_time()
            return  
        if self.sockaddr:
            self.send_data(self.netpacket, self.sockaddr)
        else:
            self.allsockaddrs = []
            try:
                for res in socket.getaddrinfo(self.bmc, self.port, 0, socket.SOCK_DGRAM):
                    sockaddr = res[4]
                    if res[0] == socket.AF_INET:
                        # convert the sockaddr to AF_INET6
                        newhost = '::ffff:' + sockaddr[0]
                        sockaddr = (newhost, sockaddr[1], 0, 0)
                    self.allsockaddrs.append(sockaddr)
                    self.bmc_handlers[sockaddr] = self
                    self.send_data(self.netpacket, sockaddr)
            except socket.gaierror:
                raise exc.IpmiException("Unable to transmit to specified address")
        if retry:
            self.waiting_sessions[self] = {}
            self.waiting_sessions[self]['ipmisession'] = self
            self.waiting_sessions[self]['timeout'] = self.timeout + _monotonic_time() 
開發者ID:rhtyd,項目名稱:ipmisim,代碼行數:31,代碼來源:fakesession.py

示例12: SyncClockToNtp

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import gaierror [as 別名]
def SyncClockToNtp(retries: int = 2, server: Text = 'time.google.com'):
  """Syncs the hardware clock to an NTP server."""
  logging.info('Reading time from NTP server %s.', server)

  attempts = 0
  client = ntplib.NTPClient()
  response = None

  while True:
    try:
      response = client.request(server, version=3)
    except (ntplib.NTPException, socket.gaierror) as e:
      logging.error('NTP client request error: %s', str(e))
    if response or attempts >= retries:
      break
    logging.info(
        'Unable to contact NTP server %s to sync machine clock.  This '
        'machine may not have an IP address yet; waiting %d seconds and '
        'trying again. Repeated failure may indicate network or driver '
        'problems.', server, RETRY_DELAY)
    time.sleep(RETRY_DELAY)
    attempts += 1

  if not response:
    raise NtpException('No response from NTP server.')

  local_time = time.localtime(response.ref_time)
  current_date = time.strftime('%m-%d-%Y', local_time)
  current_time = time.strftime('%H:%M:%S', local_time)
  logging.info('Current date/time is %s %s', current_date, current_time)

  date_set = r'%s\cmd.exe /c date %s' % (WINPE_SYSTEM32, current_date)
  result = subprocess.call(date_set, shell=True)
  logging.info('Setting date returned result %s', result)
  time_set = r'%s\cmd.exe /c time %s' % (WINPE_SYSTEM32, current_time)
  result = subprocess.call(time_set, shell=True)
  logging.info('Setting time returned result %s', result) 
開發者ID:google,項目名稱:glazier,代碼行數:39,代碼來源:ntp.py

示例13: _is_ipv6_enabled

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import gaierror [as 別名]
def _is_ipv6_enabled():
    """Check whether IPv6 is enabled on this host."""
    if socket.has_ipv6:
        sock = None
        try:
            sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
            sock.bind(('::1', 0))
            return True
        except (socket.error, socket.gaierror):
            pass
        finally:
            if sock:
                sock.close()
    return False 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:16,代碼來源:support.py

示例14: get_names

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import gaierror [as 別名]
def get_names(self):
        if FileHandler.names is None:
            try:
                FileHandler.names = tuple(
                    socket.gethostbyname_ex('localhost')[2] +
                    socket.gethostbyname_ex(socket.gethostname())[2])
            except socket.gaierror:
                FileHandler.names = (socket.gethostbyname('localhost'),)
        return FileHandler.names

    # not entirely sure what the rules are here 
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:13,代碼來源:request.py

示例15: _safe_gethostbyname

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import gaierror [as 別名]
def _safe_gethostbyname(host):
    try:
        return socket.gethostbyname(host)
    except socket.gaierror:
        return None 
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:7,代碼來源:request.py


注:本文中的socket.gaierror方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。