user1106551
user1106551

Reputation:

How do I get IPV6 address with Django?

Django and everything are running on a server. When a user from his/her local machine accesses the application, I need to save the IPV4 and IPV6 from this local machine into a form.

This is the view I'm using to save data:

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))

But with this view I'm not sure if the field I'm using to save the IPV4 is picking only the IPV4 address from where Django is running, which is the server. I guess it won't pick the IPV4 address from the local machine that I need.

Many thanks in advance from any help you can give to me.

Upvotes: 5

Views: 3701

Answers (2)

Steve K
Steve K

Reputation: 11369

It would be wise to recall that when you have an IPv4, you can retrieve the matching IPv6. IPv4 is a subnet of IPv6 so the translation to v6 is quite straightforward. You would then spare an HTTP request to your server.

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318508

You can only get the IP address the user used to access your site, i.e. the IPv4 or the IPv6 but not both. The current IP address is available via request.META['REMOTE_ADDR']

However, there is a rather easy way to get both:

  • 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.

Upvotes: 5

Related Questions