Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a viewer's IP address with python?

Tags:

python-2.7

Just doing a basic forum with a python file allowing the user to login and/or create an account. Thought I would do a little bit more and have each user logged in with their IP address and then be able to post with a unique ID generated from their IP address, like most imageboards.

I can write the code pretty easily, but I am having trouble finding how to get the user's IP address without using Flask.

EDIT: this is the code i just checked, and it seems to be working

    #!/usr/bin/python
import md5, cgi,cgitb,codecs
def Maker():
    form=cgi.FieldStorage()#for use later
    a=form.keys()#for use later
    page = 'Content-type: text/html\n\n'
    page +='<html><head><title>Test Form</title></head>\n'
    from socket import gethostname, gethostbyname 
    ip = gethostbyname(gethostname())
    page+= ip
    return page
print Maker()

EDIT: that code isnt working, still looking for help

like image 887
Konrad Avatar asked Sep 02 '25 17:09

Konrad


2 Answers

It sounds like you're running this as a CGI script. The user's IP address will be in the REMOTE_ADDR environment variable, os.environ["REMOTE_ADDR"].

like image 198
axblount Avatar answered Sep 05 '25 02:09

axblount


I think this might work

from socket import gethostname, gethostbyname 
ip = gethostbyname(gethostname()) 

or If you are using CGI you can get it from the REMOTE_ADDR environmental variable

like image 35
rcbevans Avatar answered Sep 05 '25 03:09

rcbevans