本文整理汇总了Python中socket.getnameinfo函数的典型用法代码示例。如果您正苦于以下问题:Python getnameinfo函数的具体用法?Python getnameinfo怎么用?Python getnameinfo使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getnameinfo函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testInterpreterCrash
def testInterpreterCrash(self):
# Making sure getnameinfo doesn't crash the interpreter
try:
# On some versions, this crashes the interpreter.
socket.getnameinfo(('x', 0, 0, 0), 0)
except socket.error:
pass
示例2: testInterpreterCrash
def testInterpreterCrash(self):
if sys.platform[:4] == 'java': return
# Making sure getnameinfo doesn't crash the interpreter
try:
# On some versions, this crashes the interpreter.
socket.getnameinfo(('x', 0, 0, 0), 0)
except socket.error:
pass
示例3: testRefCountGetNameInfo
def testRefCountGetNameInfo(self):
# Testing reference count for getnameinfo
if hasattr(sys, "getrefcount"):
try:
# On some versions, this loses a reference
orig = sys.getrefcount(__name__)
socket.getnameinfo(__name__, 0)
except TypeError:
self.assertEqual(sys.getrefcount(__name__), orig, "socket.getnameinfo loses a reference")
示例4: testRefCountGetNameInfo
def testRefCountGetNameInfo(self):
# Testing reference count for getnameinfo
if hasattr(sys, "getrefcount"):
try:
# On some versions, this loses a reference
orig = sys.getrefcount(__name__)
socket.getnameinfo(__name__,0)
except SystemError:
if sys.getrefcount(__name__) <> orig:
self.fail("socket.getnameinfo loses a reference")
示例5: validate
def validate(self, key, client_addr, cert_principals=None, ca=False):
for entry in self._ca_entries if ca else self._user_entries:
if entry.key != key:
continue
from_patterns = entry.options.get('from')
if from_patterns is not None:
client_host, _ = socket.getnameinfo((client_addr, 0),
socket.NI_NUMERICSERV)
client_ip = ip_address(client_addr)
if not all(pattern.matches(client_host, client_addr, client_ip)
for pattern in from_patterns):
continue
principal_patterns = entry.options.get('principals')
if cert_principals is not None and principal_patterns is not None:
if not all(any(pattern.matches(principal)
for principal in cert_principals)
for pattern in principal_patterns):
continue
return entry.options
return None
示例6: getpeernameinfo
def getpeernameinfo(self):
"""Returns (remote, port, family) tuple
"""
(addr, port) = socket.getnameinfo(self.socket.getpeername(),
socket.NI_NUMERICHOST | socket.NI_NUMERICSERV)
return (addr, port, self.socket.family)
示例7: canonicalize_dns
def canonicalize_dns(inhost, family=socket.AF_UNSPEC):
"Canonicalize a hostname or numeric IP address."
if inhost in canonicalization_cache:
return canonicalization_cache[inhost]
# Catch garbaged hostnames in corrupted Mode 6 responses
m = re.match("([:.[\]]|\w)*", inhost)
if not m:
raise TypeError
(hostname, portsuffix) = portsplit(inhost)
try:
ai = socket.getaddrinfo(hostname, None, family, 0, 0, socket.AI_CANONNAME)
except socket.gaierror as e:
print('getaddrinfo failed: %s' % e, file=sys.stderr)
raise SystemExit(1)
(family, socktype, proto, canonname, sockaddr) = ai[0]
try:
name = socket.getnameinfo(sockaddr, socket.NI_NAMEREQD)
result = name[0].lower() + portsuffix
except socket.gaierror:
# On OS X, canonname is empty for hosts without rDNS.
# Fall back to the hostname.
canonicalized = canonname or hostname
result = canonicalized.lower() + portsuffix
canonicalization_cache[inhost] = result
return result
示例8: _validate_ip_address
def _validate_ip_address(family, address):
"""Check if `address` is valid IP address and return it, in a normalized
form.
:Parameters:
- `family`: ``socket.AF_INET`` or ``socket.AF_INET6``
- `address`: the IP address to validate
"""
try:
info = socket.getaddrinfo(address, 0, family, socket.SOCK_STREAM, 0,
socket.AI_NUMERICHOST)
except socket.gaierror as err:
logger.debug("gaierror: {0} for {1!r}".format(err, address))
raise ValueError("Bad IP address")
if not info:
logger.debug("getaddrinfo result empty")
raise ValueError("Bad IP address")
addr = info[0][4]
logger.debug(" got address: {0!r}".format(addr))
try:
return socket.getnameinfo(addr, socket.NI_NUMERICHOST)[0]
except socket.gaierror as err:
logger.debug("gaierror: {0} for {1!r}".format(err, addr))
raise ValueError("Bad IP address")
示例9: match_options
def match_options(self, client_addr, cert_principals, cert_subject=None):
"""Match "from", "principals" and "subject" options in entry"""
from_patterns = self.options.get('from')
if from_patterns:
client_host, _ = socket.getnameinfo((client_addr, 0),
socket.NI_NUMERICSERV)
client_ip = ip_address(client_addr)
if not all(pattern.matches(client_host, client_addr, client_ip)
for pattern in from_patterns):
return False
principal_patterns = self.options.get('principals')
if cert_principals is not None and principal_patterns is not None:
if not all(any(pattern.matches(principal)
for principal in cert_principals)
for pattern in principal_patterns):
return False
subject_patterns = self.options.get('subject')
if cert_subject is not None and subject_patterns is not None:
if not all(pattern.matches(cert_subject)
for pattern in subject_patterns):
return False
return True
示例10: __init__
def __init__(self, parent, server):
"""
Initialize a HeyU client application.
:param parent: The parent of the ``HubApplication``. This
will be an instance of ``tendril.Tendril``.
:param server: The underlying HeyU server instance. The
server keeps track of subscriptions and
forwards notifications to the subscribers.
"""
# Initialize the application
super(HubApplication, self).__init__(parent)
# Save the server link
self.server = server
# Are we a persistent connection?
self.persist = False
# Set up the desired framer
parent.framers = tendril.COBSFramer(True)
# Determine the hostname of the client
try:
if parent.remote_addr[0] in ('127.0.0.1', '::1'):
self.hostname = socket.getfqdn()
else:
self.hostname, _port = socket.getnameinfo(parent.remote_addr,
0)
except Exception:
# Just use the bare address
self.hostname = parent.remote_addr[0]
示例11: update
def update(self, s):
self.win.erase()
self.addstr(1, 0, "CLIENT PORT S I QUEUED RECVD SENT", curses.A_REVERSE)
self.sessions[s.server_id] = s.sessions
items = []
for l in self.sessions:
items.extend(l)
items.sort(key=lambda x: int(x.queued), reverse=True)
for i, session in enumerate(items):
try:
# ugh, need to handle if slow - thread for async resolver?
if options.names:
session.host = socket.getnameinfo((session.host, int(session.port)), 0)[0]
self.addstr(
i + 2,
0,
"%-15s %5s %1s %1s %8s %8s %8s"
% (
session.host[:15],
session.port,
session.server_id,
session.interest_ops,
session.queued,
session.recved,
session.sent,
),
)
except:
break
示例12: listen
def listen(self):
if __debug__:
self.err_log.debug('Entering main loop.')
while True:
try:
sock, addr = self.listener.accept()
if self.secure:
sock = self.wrap_socket(sock)
self.active_queue.put((
(sock, socket.getnameinfo(addr, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV)),
self.interface[1],
self.secure
))
except socket.timeout:
# socket.timeout will be raised every THREAD_STOP_CHECK_INTERVAL
# seconds. When that happens, we check if it's time to die.
if not self.ready:
if __debug__:
self.err_log.debug('Listener exiting.')
try:
self.listener.shutdown(socket.SHUT_RDWR)
except socket.error:
self.err_log.warning('Socket shutdown() failed')
self.listener.close()
return
else:
continue
except:
self.err_log.error(str(traceback.format_exc()))
示例13: setup
def setup(self):
# some hack for mapped IPv4-to-IPv6 addresses
ip = IPy.IP(self.client_address[0])
if ip.iptype() == "IPV4MAP":
self.client_address = (ip._getIPv4Map().strNormal(), self.client_address[1])
client_name = socket.getnameinfo(self.client_address, socket.NI_NUMERICSERV)
self.logger = logging.getLogger("ffcontroller.control-connection")
threading.current_thread().setName(client_name[0])
self.start_time = datetime.datetime.now()
self.last_command_time = self.start_time
self.commands_sent = 0
self.queue = MixedQueue(global_queue)
# start dedicated server for us
self.proxy_server = start_server(
ThreadedHTTPServer,
HTTPProxyRequestHandler,
options.proxy_address,
proxy_port_range.popleft(),
ServerConnectionPool(self.queue),
)
# register self for statistics
control_connections.append(self)
self.logger.debug("started")
socketserver.StreamRequestHandler.setup(self)
self.connection.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
示例14: connect
def connect(self):
# create listening socket for back connection
backserv = socket.socket()
backserv.settimeout(options.backconn_timeout)
# bind to some unused port
backserv.bind((options.backconn_address, 0))
selfaddr = backserv.getsockname()
selfnetloc = "{0}:{1}".format(*selfaddr)
self.logger.debug("awaiting back connection on {0}".format(selfnetloc))
# start listening
backserv.listen(1)
for i in range(options.retry_count):
# put both locations to queue
self.queue.put((selfnetloc, self.netloc))
# wait for connection
try:
self.sock, peeraddr = backserv.accept()
self.sock.settimeout(options.transport_timeout)
break
except socket.timeout:
self.logger.info("timeout while accepting back connection. resending request.")
else:
raise socket.timeout("timeout while trying to establish back connection")
self.logger.debug(
"accepted back connection from {0}:{1}".format(*socket.getnameinfo(peeraddr, socket.NI_NUMERICSERV))
)
# close server socket
backserv.close()
示例15: getHostnameFqdn
def getHostnameFqdn():
"""
Wrapper around getfqdn.
Returns the fully qualified hostname, None if not found.
"""
try:
sHostname = socket.getfqdn();
except:
return None;
if '.' in sHostname or sHostname.startswith('localhost'):
return sHostname;
#
# Somewhat misconfigured system, needs expensive approach to guessing FQDN.
# Get address information on the hostname and do a reverse lookup from that.
#
try:
aAddressInfo = socket.getaddrinfo(sHostname, None);
except:
return sHostname;
for aAI in aAddressInfo:
try: sName, _ = socket.getnameinfo(aAI[4], 0);
except: continue;
if '.' in sName and not set(sName).issubset(set('0123456789.')) and not sName.startswith('localhost'):
return sName;
return sHostname;