user1618465
user1618465

Reputation: 1941

Add the Http_X_Forwarded_For header in a request in python

I have a small PHP code in a web server. The PHP code just logs the IP of the people that do a request with this line:

    $ip = !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
echo 'Your IP is:'.$ip

I want to create a piece of code in Python that uses the HTTP_X_FORWARDED_FOR header to force the webserver to log other IP than the real one. I have written this code:

import urllib2,cookielib

cj = cookielib.CookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('HTTP_X_FORWARDED_FOR','1.2.3.4'),]
resp=opener.open('http://example.com/logIP.php')

Why doesn't the PHP code 1.2.3.4 if I have set it in my Python code? How can I force the web app to show the "fake" IP?

Upvotes: 3

Views: 7004

Answers (1)

r3m0t
r3m0t

Reputation: 1870

The header should be X-Forwarded-For on the urllib (Python) side. Your webserver then reads that into the HTTP_X_FORWARDED_FOR environment variable which you read from $_SERVER.

opener.addheaders = [('X-Forwarded-For','1.2.3.4'),]

Upvotes: 6

Related Questions