【问题标题】:socket.gethostbyname not working for my ddns hostnamesocket.gethostbyname 不适用于我的 ddns 主机名
【发布时间】:2016-06-01 10:05:24
【问题描述】:

我有以下代码来 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 的错误消息是

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

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

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

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

【问题讨论】:

    标签: python sockets dns ping


    【解决方案1】:

    查询不带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?

    【讨论】:

    • 现在看起来很明显。我没有考虑使用两者。感谢您的帮助
    • @TheStudent 事后看来总是更明显。很高兴我能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 2013-04-02
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 2022-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多