IP Address Function

Piet van Oostrum piet at cs.uu.nl
Wed Jul 8 06:29:54 EDT 2009


>>>>> Fred Atkinson <fatkinson at mishmash.com> (FA) wrote:

>FA> On Tue, 07 Jul 2009 22:54:03 -0300, "Gabriel Genellina"
>FA> <gagsl-py2 at yahoo.com.ar> wrote:

>>> En Tue, 07 Jul 2009 22:45:24 -0300, Fred Atkinson <fatkinson at mishmash.com>  
>>> escribió:
>>> 
>>>> Is there a Python function I can use to get the user's IP
>>>> address so I can display it on his browser?
>>> 
>>> There is a long distance between "Python" and "browser" - you'll have to  
>>> tell us what is in between the two.

>FA> 	I want to have a Web page come up (written in Python, cgi)
>FA> that returns the IP address of the browser (user's PC's IP address).  

>>> By example, do you have a server and the user connects to it? is it  
>>> running Python? how do you run the Python application?
>>> And why do you want to do that on the server side? Isn't easier to do that  
>>> on the client side? What about proxies? NAT?

>FA> 	Yes.  By CGI.  

>>> If using CGI, look at the REMOTE_ADDR environment variable.

>FA> 	I did look at REMOTE_ADDR but I've been unable to figure out
>FA> the correct way to code it.  I've tried a number of ways but I've been
>FA> unsuccessful.  

>FA> 	Ideally, I'd like to store the brower's IP address in a string
>FA> and then print the string on the Web page from a Python CGI script.  

Something like:

#! /usr/bin/env python

import cgi
from os import getenv

print "Content-type: text/html"
print

ipaddr = (getenv("HTTP_CLIENT_IP") or
      getenv("HTTP_X_FORWARDED_FOR") or
      getenv("HTTP_X_FORWARDED_FOR") or
      getenv("REMOTE_ADDR") or
      "UNKNOWN")

print ipaddr


-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list