2013-06-19 60 views
1

我使用的Django ipware用於獲取用戶的公網IPDjango的給我本地IP總是在我的網站

https://github.com/un33k/django-ipware

我的網站託管在通過虛擬機djnago , mod_wsgi , apache

這是我的代碼

g = GeoIP() 
    ip_address = get_ip_address_from_request(self.request) 
    raise Exception(ip_address) 

它給了我127.0.0.1

我正在通過同一網絡上的其他計算機訪問它。

我怎樣才能讓我的公網IP

我也試過這個問題,以及

PRIVATE_IPS_PREFIX = ('10.', '172.', '192.',) 

def get_client_ip(request): 
"""get the client ip from the request 
""" 
remote_address = request.META.get('REMOTE_ADDR') 
# set the default value of the ip to be the REMOTE_ADDR if available 
# else None 
ip = remote_address 
# try to get the first non-proxy ip (not a private ip) from the 
# HTTP_X_FORWARDED_FOR 
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') 
if x_forwarded_for: 
    proxies = x_forwarded_for.split(',') 
    # remove the private ips from the beginning 
    while (len(proxies) > 0 and 
      proxies[0].startswith(PRIVATE_IPS_PREFIX)): 
     proxies.pop(0) 
    # take the first ip which is not a private one (of a proxy) 
    if len(proxies) > 0: 
     ip = proxies[0] 

return ip 

這回我192.168.0.10我的本地計算機的IP

+0

1.閱讀這個 [問題] [1] 2. VM的讀取文檔 [1]:http://stackoverflow.com/questions/4581789/我怎麼做,我用戶的IP地址在Django –

+0

@AlokTiwari我已經閱讀該帖子,我從那篇文章中得到了我的解決方案。但找不到解決方案 – user1958218

+1

您不會在您的局域網上獲取您的公共IP,因爲它永遠不會通過該接口進行代理。 – DivinusVox

回答

1

Django的ipware試圖獲取客戶端的(例如,瀏覽器)公共(可外部路由的)IP地址,因此它不能這樣做,因此,它會根據其文檔(版本0.0.1)返回指示故障的「127.0.0.1」(本地回送,IPv4)。

因爲您的服務器與您自己的本地計算機在同一個(專用)網絡上運行,所以發生這種情況。 (192.168.x.x專用塊)

您可以升級到版本django-ipware> = 0.0.5,它支持IPv4 & IPv6,並按以下方式使用它。

# if you want the real IP address (public and externally route-able) 
from ipware.ip import get_real_ip 
ip = get_real_ip(request) 
if ip is not None: 
    # your server got the client's real public ip address 
else: 
    # your server doesn't have a real public ip address for user 


# if you want the best matched IP address (public and/or private) 
from ipware.ip import get_ip 
ip = get_ip(request) 
if ip is not None: 
    # your server got the client's real ip address 
else: 
    # your server doesn't have a real ip address for user 

####### NOTE: 
# A `Real` IP address is the IP address of the client accessing your server 
# and not that of any proxies in between. 
# A `Public` IP address is an address that is publicly route-able on the internet. 
相關問題