从烧瓶中的用户那里获取正确的IP地址

时间:2018-08-27 08:27:08

标签: python email ip

我在StackOverflow的这个线程上看到过:How to find location with IP address in Python?

答案对我有用,但是到目前为止,我仅在localhost上进行了测试,并且我想确保IP地址实际上是来自用户的IP,而不是服务器本身。

我之所以有疑问,是因为我尝试了不同的方法对其进行测试

 #I'm using a Mail API, but here I will print for simplicity
'IP-address from user ' + request.remote_addr #retures 127.0.0.1 when running on localhost

每当尝试使用ipinfo API时,都会从Internet连接而不是从本地主机获取实际的IP地址。

url= 'http://ipinfo.io/json'
response = urlopen(url)
data = json.load(response)

IP=data['ip']
org=data['org']
city = data['city']
country=data['country']
region=data['region']  

 print('IP : {4} \nRegion : {1} \nCountry : {2} \nCity : {3} \nOrg : {0}'.format(org,region,country,city,IP))
#returns actual IP-address from my internet connection

如何确保以后的解决方案实际从用户那里返回IP和位置,才能访问服务

1 个答案:

答案 0 :(得分:1)

request.remote_addr为您提供请求所来自的地址 。如果您是在本地主机上运行它,那么是的,请求也将来自本地主机,所以这就是您获得的IP。

如果您的服务器设置为某些特定的代理配置,那么您的服务器看到的所有传入请求都是代理的IP,那么您应该知道就是这种情况(因为您是通过这种方式设置服务器的),并确保代理以其他某种方式(即HTTP标头)传递访问者的IP,并专门使用它代替request.remote_addr。同样,您会知道是否以及何时处于这种情况。

当您从服务器向ipinfo.io 请求时,ipinfo.io会将服务器的地址视为请求的发起者,并将其用作您的IP地址在问。由于请求是通过Internet进行的,因此它会看到您的公共Internet地址。如果您希望服务器查询访问者的IP,则服务器将需要在请求中包含访问者的IP,否则ipinfo.io将没有机会知道该IP。然后,该请求应如下所示:

url = 'http://ipinfo.io/' + request.remote_addr