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

2024-05-16 04:06:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码ping我的ddns主机名,并在主机启动或关闭时返回。然后我尝试添加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的错误消息是

^{pr2}$

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

我也尝试过使用来自How do I get the IP address from a http request using the requests library?的代码,但没有成功。在

使用这个工具(http://mxtoolbox.com/SuperTool.aspx#)我确认在DNS中有一个A记录网址:ssmale.ddns.net在

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


Tags: inpyhttpurlnetrequestlibpackages
1条回答
网友
1楼 · 发布于 2024-05-16 04:06:16

查询没有http://部分的地址:

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

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

^{pr2}$

在我的机器上工作:

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

相关问题 更多 >