我正在开发一个Django项目,用户可以根据自己的位置获得自定义信息。为此,我使用他们的IP地址来识别他们的国家。为了保持数据库中的数据一致,我需要确保我有一个准确的IP。
我知道使用META通常会使用客户端浏览器发送的标头,但我不知道这是否适用于REMOTE_ADDR
属性。
TLDR:HttpRequest.get_host()
和HttpRequest.META['REMOTE_ADDR']
之间有什么区别?
答案 0 :(得分:6)
HttpRequest.get_host()
和HttpRequest.META['REMOTE_ADDR']
之间的区别在于,第一个按优先级递减的顺序检查以下标头中的IP:
HTTP_X_FORWARDED_HOST
HTTP_HOST
SERVER_NAME combined with SERVER_PORT
而第二个检查标题REMOTE_ADDR
中的IP。
返回的信息类型存在巨大差异:get_host()
将为您提供托管应用程序的服务器的名称,而不是客户端的IP。
更详细地说,这是get_host()
的实现:
def get_host(self):
"""Returns the HTTP host using the environment or request headers."""
# We try three options, in order of decreasing preference.
if settings.USE_X_FORWARDED_HOST and (
'HTTP_X_FORWARDED_HOST' in self.META):
host = self.META['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in self.META:
host = self.META['HTTP_HOST']
else:
# Reconstruct the host using the algorithm from PEP 333.
host = self.META['SERVER_NAME']
server_port = str(self.META['SERVER_PORT'])
if server_port != ('443' if self.is_secure() else '80'):
host = '%s:%s' % (host, server_port)
allowed_hosts = ['*'] if settings.DEBUG else settings.ALLOWED_HOSTS
domain, port = split_domain_port(host)
if domain and validate_host(domain, allowed_hosts):
return host
else:
msg = "Invalid HTTP_HOST header: %r." % host
if domain:
msg += "You may need to add %r to ALLOWED_HOSTS." % domain
raise DisallowedHost(msg)
如果您想检查客户端IP地址,可以参考以下标题(参见Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?):
REMOTE_ADDR
HTTP_X_FORWARDED_FOR
HTTP_CLIENT_IP
HTTP_X_FORWARDED_FOR
可以是逗号分隔的IP列表HTTP_X_FORWARDED
HTTP_X_CLUSTER_CLIENT_IP
HTTP_FORWARDED_FOR
HTTP_FORWARDED
如果您不知道要选择哪一个(如果不是全部),您可以记录这些标题并实际添加新的检查。