0

In my code i want to know the ip address of the client from which the api call is made. Is there any way?

eg: Assume some guy initiated this api call like"http://server_url/api/v1/range/setup/"

In my api.py in server can i read the ip address of his machine ?

CodeJunkie
  • 147
  • 1
  • 2
  • 13
  • I assume you're using django.. if so see [this](http://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django). Please also add what have you got so far.. – Acsisr Aug 13 '14 at 12:29

1 Answers1

3

I once used this method, which should return IP address from your request meta data:

def getClientIPaddress(request):
    http_x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if http_x_forwarded_for:
        ip_address = http_x_forwarded_for.split(',')[0]
    else:
        ip_address = request.META.get('REMOTE_ADDR')
    return ip_address

Then you can call getClientIPaddress method from whereever you process your API call, eg:

class YourResource(ModelResource):
    class Meta:
        #meta code here

    def obj_create(self, bundle, **kwargs):
        ip = getClientIPaddress(bundle.request)
        #your code here

    def obj_get_list(self, bundle, **kwargs):
        ip = getClientIPaddress(bundle.request)
        #your code here
Matúš Bartko
  • 2,425
  • 2
  • 30
  • 42