-1

Is there any way to get the IP address in pure python (not Django)?

I found the code bellow, but i do not have a Request object.

def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[-1].strip()
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip
Eduardo
  • 1,698
  • 4
  • 29
  • 48

3 Answers3

0

If you're talking about your local machine a quick google search found this:

Finding local IP addresses using Python's stdlib

Community
  • 1
  • 1
djhoese
  • 3,567
  • 1
  • 27
  • 45
0

It sounds like you are saying that you have a socket object that is the result of an earlier accept call. If so, that socket object will have a getpeername attribute:

result = descriptor.getpeername()

If it's an IP socket the result will be the (hostaddr, port) pair.

torek
  • 448,244
  • 59
  • 642
  • 775
-1

You can get the local IP adress using the socket module

>>> import socket
>>> socket.gethostbyname(socket.gethostname())
Abhijit
  • 62,056
  • 18
  • 131
  • 204