如何在Django中获取IPv6地址?

5

Django和所有内容都运行在服务器上。当用户从他/她的本地机器访问应用程序时,我需要将此本地机器的IPV4和IPV6保存到表单中。

这是我正在使用的视图来保存数据:

def t031003form_save(request):
    form = T031003Form(request.POST or None, request.FILES or None)
    if request.method == 'POST':
        if form.is_valid():
            form = form.save(False)
            form.C003LOGB = datetime.date.today()
            form.C003LOGD = socket.gethostbyname(socket.gethostname())
            form.save()
            form = T031003Form()
        else:
           return HttpResponseRedirect('/erro/')
    return render_to_response('T031003Form_save.html', {'form': form,}, context_instance=RequestContext(request))

但是,我不确定我用来保存IPV4的字段是否只选择从Django运行的地方(即服务器)获取IPV4地址。我猜它不会选择我需要的本地机器上的IPV4地址。

非常感谢您提供的任何帮助。

2个回答

5

您只能获取用户访问您网站时使用的IP地址,即IPv4IPv6中的一个。当前IP地址可以通过request.META['REMOTE_ADDR']获取。

但是,还有一种相对简单的方法可以同时获取两者:

  • Create two subdomains, v4.yourdomain.tld and v6.yourdomain.tld which are only reachable via IPv4/6.
  • On your actual page, generate a random token that is associated with the user and create a script tag:

    <script src="//vX.yourdomain.tld/?token=YYY"></script>
    

    If the user accessed your page via IPv4, use X=6, otherwise X=4.

  • In your code that runs when accessing one of the subdomains, log the IP for the user identified by the token.

0

需要注意的是,当您拥有IPv4时,可以检索相匹配的IPv6。 IPv4是IPv6的子网,因此转换为v6非常简单。然后,您将节省向服务器发出的HTTP请求。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接