【问题标题】:python: check if a hostname is resolvedpython:检查主机名是否已解析
【发布时间】:2012-07-23 18:16:06
【问题描述】:

如何在 python 中创建一个函数,如果主机名解析则返回 1,如果主机名不解析则返回 0。

我找不到任何有用的东西,有什么想法吗?

谢谢,

【问题讨论】:

  • 返回 0/1 是非常“unpythonic”而不是 True/False。这将是一些非常具体的代码,甚至可以将它们区分为1 == True0 == FalseTrue + True == 2sum(n % 2 == 0 for n in range(1000)) == 500

标签: python hostname


【解决方案1】:

您可以为此使用socket.gethostbyname()

>>> import socket
>>> socket.gethostbyname('google.com')
'74.125.224.198'
>>> socket.gethostbyname('foo')           # no host 'foo' exists on the network
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.gaierror: [Errno 8] nodename nor servname provided, or not known

您的函数可能如下所示:

def hostname_resolves(hostname):
    try:
        socket.gethostbyname(hostname)
        return 1
    except socket.error:
        return 0

例子:

>>> hostname_resolves('google.com')
1
>>> hostname_resolves('foo')
0

【讨论】:

  • 一分钟前刚刚看到...除了返回 0 和 1,我需要尝试一下。谢谢!
  • 我认为他可能有,但问题明确要求 0 和 1。也许您的评论最好指向问题作者。
猜你喜欢
  • 2014-07-04
  • 1970-01-01
  • 2020-07-12
  • 2022-01-09
  • 2015-04-28
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
相关资源
最近更新 更多