Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: CGI program wants to know the IP address of the calling web page

I am new to Python programming.

I am stuck on what should be a simple procedure. I have a small and basic Python program that is called as CGI program by a web page.

All that I want to do is extract the IP address from the HTTP header fields. For example, in PHP, this would be the value of $_SERVER['REMOTE_ADDR'].

I paid my dues by doing a search, and I came up with the fact that I need to use web.ctx.ip, but when I use that bit in code, there is an exception. I probably need to import something. I've tried the following individual imports without success:

import web
import webapi as web

I'd appreciate a complete snippet of code that demonstrates what I need to import. My Python CGI program is running on a Linux box that has a basic Python version 2.4.3 installed. Do I need to install something else?

like image 593
Ray Goudie Avatar asked Aug 11 '11 23:08

Ray Goudie


People also ask

How do you program CGI in Python?

First CGI Program Here is a simple link, which is linked to a CGI script called hello.py. This file is kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program, make sure you have change mode of file using chmod 755 hello.py UNIX command to make file executable.

What is CGI How do you configure CGI in Python?

CGI stands for Common Gateway Interface in Python which is a set of standards that explains how information or data is exchanged between the web server and a routine script.

What is CGI in URL?

The Common Gateway Interface (CGI) is a method of allowing a hyperlink to refer to a program rather than a static web page. The easiest way to understand how a CGI works is by contrast with an ordinary web page.


2 Answers

From here:

# When run as a cgi script, this will print the client's IP address.

import html
import os

print("Content-type: text/html")
print("")

print html.escape(os.environ["REMOTE_ADDR"])

The search was for "python cgi get ip address" and it was the first result. This answer is for generic Python CGI, if you're using some other interface / library then it might be different. It is the exact analog of the PHP version, however, as you can see.

like image 186
agf Avatar answered Oct 06 '22 11:10

agf


The example above worked great for me. I added a little extra for local testing. I had to search for a long time to find this example so "thank you!"

import cgi
import os

def f_get_ipaddress():
    try:
        ipaddress = cgi.escape(os.environ["REMOTE_ADDR"])
    except:
        ipaddress = "127.0.0.1"

    return ipaddress

print "Content-type: text/html"
print ""

ipaddress = f_get_ipaddress()

print ipaddress
like image 24
codehawk Avatar answered Oct 06 '22 11:10

codehawk