如何在Bottle Python中获取客户端主机名?

时间:2018-09-20 10:54:32

标签: python-3.x bottle

from bottle import Bottle, request
import socket

app = Bottle()
my_ip = socket.gethostbyname(socket.gethostname())

@app.route('/hello')
def hello():
    client_ip = request.environ.get('REMOTE_ADDR')
    print("Client IP is ", client_ip)

    #Code to read client hostname or machine name

    return ['Your IP is: {}\n'.format(client_ip)]

app.run(host=my_ip, port=8080)

我正在使用瓶子(适用于Python的WSGI微型网络框架)。我知道如何获取请求服务的客户的IP。但我也想知道客户端的主机名(计算机名)。 我尝试使用Windows命令(如nbtstat和ping)读取主机名,但它们并非100%可靠。还有其他选择吗?

1 个答案:

答案 0 :(得分:0)

几件事:

  1. 完全不这样做可能会更好。相反,可以考虑将所有IP地址记录到文件中(更好的是,什么也不做,仅使用现有的access_log),然后批量脱机解决它们。

  2. 如果您坚持要内联解析IP地址,则无需调出Windows命令即可。 解析处理中的地址会更快,更简单,更可靠。我在下面为您提供了一些示例代码。

  3. 最后,我想发表您的评论:

  

我尝试过...但是它们不是100%可靠

这是您的期望问题,而不是DNS解析器问题。反向DNS查找本质上会产生远远少于100%匹配项。

以下是在Python中进行反向查找的示例代码。祝你好运!

from socket import gethostbyaddr, herror

def resolve_address(addr):
    '''
    Resolve the ip address string ``addr`` and return its DNS name. If no name
    is found, return None.

    Raises any exceptions thrown by gethostbyaddr, except for NOTFOUND (which
    is handled by returning None).

    NOTE: Illustrative purposes only, not for production use.
    '''

    try:
        record = gethostbyaddr(addr)

    except herror as exc:
        if exc.errno == 1:
            print(f'no name found for address "{addr}"')
            return None
        else:
            print(f'an error occurred while resolving {addr}: {exc}')
            raise

    print(f'the name of "{addr}" is: {record[0]}')
    return record[0]

assert resolve_address('151.236.216.85') == 'li560-85.members.linode.com'
assert resolve_address('10.1.1.1') is None