python:检查主机名是否已解析 [英] python: check if a hostname is resolved

查看:135
本文介绍了python:检查主机名是否已解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何在python中使用一个函数,如果主机名解析则返回1,如果主机名没有解析,则返回0.

How can I have a function in python that returns 1 if the a hostname resolves and 0 if a hostname does not.

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

I couldn't find anything useful, any thoughts?

谢谢

推荐答案

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

You can use socket.gethostbyname() for this:

>>> 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

您的函数可能如下所示:

Your function might look like this:

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

示例:

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

这篇关于python:检查主机名是否已解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆