socket.gethostbyname 不适用于我的 ddns 主机名

socket.gethostbyname not working for my ddns hostname

我有以下代码来 ping 我的 ddns 主机名和 return 如果主机是启动还是关闭。然后我尝试添加 socket.gethostbyname ,它适用于我的正常主机名 www.iamsimonsmale.co.uk 但不适用于 http://ssmale.ddns.net.

我试图从地址的开头删除 http://,但也失败了。

#!/usr/bin/env python
# This script checks to see if the server is up or down and prints the pinged IP

import requests
import socket
import time

while True:

    host = 'http://ssmale.ddns.net'

    ip = socket.gethostbyname(host)

    print ip

    response = requests.get(host)
    if response.status_code == requests.codes.ok:
        print('Server Up')
    else:
        print('Server Down')
    time.sleep(10)

http://ssmale.ddns.net 的错误消息是

Traceback (most recent call last):
File "PingTestIP.py", line 12, in <module>
ip = socket.gethostbyname('http://ssmale.ddns.net')
socket.gaierror: [Errno -2] Name or service not known

ssmale.ddns.net

Traceback (most recent call last):
File "PingTestIP.py", line 16, in <module>
response = requests.get(host)
File "/usr/lib/python2.7/dist-packages/requests/api.py", line 60, in get
return request('get', url, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/api.py", line 49, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 443, in request
prep = self.prepare_request(req)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 374, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "/usr/lib/python2.7/dist-packages/requests/models.py", line 304, in prepare
self.prepare_url(url, params)
File "/usr/lib/python2.7/dist-packages/requests/models.py", line 358, in prepare_url
"Perhaps you meant http://{0}?".format(url))
requests.exceptions.MissingSchema: Invalid URL u'ssmale.ddns.net': No schema supplied. Perhaps you meant http://ssmale.ddns.net?

并且当使用 `www.iamsimonsmale.co.uk 完成后它工作并且打印是

86.136.251.202
Server Up

我也曾尝试使用 中的代码,但没有成功。

使用此工具 (http://mxtoolbox.com/SuperTool.aspx#) 我确认在 ssmale.ddns.net

的 DNS 中有一条 A 记录

是什么导致了这个问题,我该如何解决?

查询不带http://部分的地址:

ip = socket.gethostbyname('ssmale.ddns.net')

然后在您的请求查询中使用完整地址:

response = requests.get("http://ssmale.ddns.net")

在我的机器上工作:

>>> import socket

>>> socket.gethostbyname("ssmale.ddns.net")
'86.136.251.202'

>>> import requests

>>> requests.get("http://ssmale.ddns.net")
<Response [200]>

您发布的错误消息已经说明了:No schema supplied. Perhaps you meant http://ssmale.ddns.net?