本文整理汇总了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
示例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
示例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
示例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!")
示例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
示例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()
示例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
示例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
示例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()
示例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()
示例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()
示例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)
示例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
示例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
示例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