本文整理匯總了Python中socket.herror方法的典型用法代碼示例。如果您正苦於以下問題:Python socket.herror方法的具體用法?Python socket.herror怎麽用?Python socket.herror使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類socket
的用法示例。
在下文中一共展示了socket.herror方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import herror [as 別名]
def __init__(self, host, port, console_host, console_port):
try:
threading.Thread.__init__(self)
self.console_host = console_host
self.console_port = console_port
self.host = host
self.port = port
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server.bind((host, port))
self.server.listen(200)
#TODO timeout in a lock section can be used to autoterminate the thread
#when inactivity and timeout<time : set timeout=0 and terminate
#from outside, close class when timeout==0; set timeout=time+120 when adding a new console on this thread
#set self.timeout = time.time() + 120 at init
self.name = "ConsoleProxy " + console_host + ":" + str(console_port)
self.input_list = [self.server]
self.channel = {}
self.terminate = False #put at True from outside to force termination
except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
if e is socket.error and e.errno==98:
raise ConsoleProxyExceptionPortUsed("socket.error " + str(e))
raise ConsoleProxyException(type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0])) )
示例2: on_close
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import herror [as 別名]
def on_close(self, sock, cause):
if sock not in self.channel:
return #can happen if there is data ready to received at both sides and the channel has been deleted. QUITE IMPROBABLE but just in case
info = self.channel[sock]
#debug info
sockname = "client" if sock is info["clientsock"] else "server"
print self.name, ": del connection %s %s at %s side" % (info["name"], cause, sockname)
#close sockets
try:
# close the connection with client
info["clientsock"].close() # equivalent to do self.s.close()
except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
print self.name, ": Exception on_close client socket %s: %s" % (type(e).__name__, str(e) )
try:
# close the connection with remote server
info["serversock"].close()
except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
print self.name, ": Exception on_close server socket %s: %s" % (type(e).__name__, str(e) )
#remove objects from input_list
self.input_list.remove(info["clientsock"])
self.input_list.remove(info["serversock"])
# delete both objects from channel dict
del self.channel[info["clientsock"]]
del self.channel[info["serversock"]]
示例3: on_recv
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import herror [as 別名]
def on_recv(self, sock):
if sock not in self.channel:
return #can happen if there is data ready to received at both sides and the channel has been deleted. QUITE IMPROBABLE but just in case
info = self.channel[sock]
peersock = info["serversock"] if sock is info["clientsock"] else info["clientsock"]
try:
data = sock.recv(self.buffer_size)
if len(data) == 0:
self.on_close(sock, "peer closed")
else:
#print self.data
sock = peersock
peersock.send(data)
except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
#print self.name, ": Exception %s: %s" % (type(e).__name__, str(e) )
self.on_close(sock, "Exception %s: %s" % (type(e).__name__, str(e) ))
#def start_timeout(self):
# self.timeout = time.time() + 120
示例4: ip2name
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import herror [as 別名]
def ip2name(addr):
if not ip2name.resolve:
return addr
try:
if addr in ip2name.cache:
return ip2name.cache[addr]
# FIXME: Workaround Python bug
# Need double try/except to catch the bug
try:
name = gethostbyaddr(addr)[0]
except KeyboardInterrupt:
raise
except (socket_host_error, ValueError):
name = addr
except (socket_host_error, KeyboardInterrupt, ValueError):
ip2name.resolve = False
name = addr
ip2name.cache[addr] = name
return name
示例5: ptr_lookup
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import herror [as 別名]
def ptr_lookup(cls, network):
ip = str(ipaddress.ip_interface(network).ip)
try:
primary_hostname, alias_hostnames, other_ips = socket.gethostbyaddr(ip)
except socket.herror as e:
logger.debug('DNS Reverse Lookup Error {}'.format(e))
return Html.div('DNS: n/a')
content = Html.div(
'DNS: {}'.format(
socket.getfqdn(primary_hostname)
)
)
if alias_hostnames:
content += Html.div('DNS Aliases:')
for hostname in alias_hostnames:
fqdn_hostname = socket.getfqdn(hostname)
logger.debug('Alias {} FQDN {}'.format(hostname, fqdn_hostname))
content += Html.div(fqdn_hostname)
return content
示例6: whois
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import herror [as 別名]
def whois(url, command=False):
# clean domain to expose netloc
ip_match = re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", url)
if ip_match:
domain = url
try:
result = socket.gethostbyaddr(url)
except socket.herror as e:
pass
else:
domain = result[0]
else:
domain = extract_domain(url)
if command:
# try native whois command
r = subprocess.Popen(['whois', domain], stdout=subprocess.PIPE)
text = r.stdout.read()
else:
# try builtin client
nic_client = NICClient()
text = nic_client.whois_lookup(None, domain, 0)
return WhoisEntry.load(domain, text)
示例7: get_local_hostname
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import herror [as 別名]
def get_local_hostname(self):
"""
Returns the local hostname under which the webinterface can be reached
:return: fully qualified hostname
:rtype: str
"""
import socket
try:
return socket.gethostbyaddr(self.get_local_ip_address())[0] # can fail with default /etc/hosts
except socket.herror:
try:
return socket.gethostbyaddr("127.0.1.1")[0] # in debian based systems hostname is assigned to "127.0.1.1" by default
except socket.herror:
try:
return socket.gethostbyaddr("127.0.0.1")[0] # 'localhost' in most cases
except socket.herror:
return "localhost" # should not happen
示例8: whois
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import herror [as 別名]
def whois(url, command=False, flags=0):
# clean domain to expose netloc
ip_match = IPV4_OR_V6.match(url)
if ip_match:
domain = url
try:
result = socket.gethostbyaddr(url)
except socket.herror as e:
pass
else:
domain = extract_domain(result[0])
else:
domain = extract_domain(url)
if command:
# try native whois command
r = subprocess.Popen(['whois', domain], stdout=subprocess.PIPE)
text = r.stdout.read().decode()
else:
# try builtin client
nic_client = NICClient()
text = nic_client.whois_lookup(None, domain.encode('idna'), flags)
return WhoisEntry.load(domain, text)
示例9: _get_reverse_dns
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import herror [as 別名]
def _get_reverse_dns(ip_address):
"""
Queries for an IP addresses reverse DNS hostname(s)
Args:
ip_address (str): An IPv4 or IPv6 address
Returns:
list: A list of reverse DNS hostnames
Raises:
:exc:`checkdmarc.DNSException`
"""
try:
results = socket.gethostbyaddr(ip_address)
hostnames = [results[0]] + results[1]
except socket.herror:
return []
except Exception as error:
raise DNSException(error)
return hostnames
示例10: start
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import herror [as 別名]
def start(self):
try:
if not self.isConnected():
await self._connect()
while self.isConnected():
await self.client.parse()
except CancelledError:
pass
except Exception as err:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
log.info("FICSConnection.run: %s" % repr(err),
extra={"task": (self.host, "raw")})
self.close()
if isinstance(err,
(IOError, LogOnException, EOFError, socket.error,
socket.gaierror, socket.herror)):
self.emit("error", err)
else:
raise
finally:
if isinstance(self, FICSMainConnection):
self.emit("disconnected")
示例11: close
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import herror [as 別名]
def close(self):
if isinstance(self.client, PredictionsTelnet) and self.set_user_vars:
self.client.run_command("set open 0")
self.client.run_command("set gin 0")
self.client.run_command("set availinfo 0")
try:
self.lvm.stop()
except AttributeError:
pass
except Exception as err:
if not isinstance(err,
(IOError, LogOnException, EOFError, socket.error,
socket.gaierror, socket.herror)):
raise
finally:
FICSConnection.close(self)
示例12: check_connection
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import herror [as 別名]
def check_connection(server="lbry.com", port=80, timeout=5) -> bool:
"""Attempts to open a socket to server:port and returns True if successful."""
log.debug('Checking connection to %s:%s', server, port)
try:
server = socket.gethostbyname(server)
socket.create_connection((server, port), timeout).close()
return True
except (socket.gaierror, socket.herror):
log.debug("Failed to connect to %s:%s. Unable to resolve domain. Trying to bypass DNS",
server, port)
try:
server = "8.8.8.8"
port = 53
socket.create_connection((server, port), timeout).close()
return True
except OSError:
return False
except OSError:
return False
示例13: check_ip_alive
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import herror [as 別名]
def check_ip_alive(ip):
"""
efficiently check if an IP address is alive or not
by using the socket.gethostbyaddr function
"""
def is_valid_ip(ip):
try:
socket.inet_aton(ip)
return True
except:
return False
try:
if not is_valid_ip(ip):
return False
else:
return socket.gethostbyaddr(ip)
except socket.herror:
return False
示例14: request
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import herror [as 別名]
def request(self, uri, method='GET', body=None, *args, **kwargs):
for i in range(1, self._max_tries + 1):
try:
response, content = self._http.request(uri, method, body, *args,
**kwargs)
if self._retrying_statuses_fn(response.status):
logging.info('RetriableHttp: attempt %d receiving status %d, %s',
i, response.status,
'final attempt' if i == self._max_tries else \
'will retry')
else:
break
except (ValueError, errors.Error,
socket.timeout, socket.error, socket.herror, socket.gaierror,
httplib2.HttpLib2Error) as error:
logging.info('RetriableHttp: attempt %d received exception: %s, %s',
i, error, 'final attempt' if i == self._max_tries else \
'will retry')
if i == self._max_tries:
raise
time.sleep(self._backoff_time)
return response, content
示例15: send
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import herror [as 別名]
def send(self, metric_pb):
body = self.encode_to_json(metric_pb)
try:
resp, content = self._http.request(self._endpoint,
method='POST',
body=body,
headers={'Content-Type': 'application/json'})
if resp.status == 200:
self._failed = False
else:
logging.warning('HttpsMonitor.send received status %d: %s', resp.status,
content)
self._failed = True
except (ValueError, errors.Error,
socket.timeout, socket.error, socket.herror, socket.gaierror,
httplib2.HttpLib2Error):
logging.exception('HttpsMonitor.send failed')
self._failed = True