Python thinks I am a different IP address

I am trying to set up a page that displays a visitor's IP address. All of the methods I've tried show an IP address different from my computer's IP. I tried:

How can I find the real IP address of a visitor?

+2


a source to share


2 answers


I found a simple solution:

import getenv
print getenv("REMOTE_ADDR")

      



This will return the IP address of the computer connected to the server.

0


a source


By using the low-level network interface, you actually get the address of the server that the python interpreter is running on:

socket.gethostname (): Returns a string containing the hostname of the machine that the Python interpreter is currently running on.

Obtaining the client's IP address using the low-level network interface

socket.accept () Accept the connection. The socket must bind to an address and listen for connections. The return value is a pair (conn, address), where conn is a new socket object that can be used to send and receive data on the connection, and the address is the address associated with the socket on the other end of the connection. "

# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.send(data)
conn.close()

      

More information on low-level network interface



Get client IP from HTTP headers (if html is used)

REMOTE_ADDR

is the header containing the client's ip address, which you should check first.

You should also check the title HTTP_X_FORWARDED

if you are a visitor going through a proxy. Keep in mind that HTTP_X_FORWARDED

is an array that can contain multiple comma-separated values ​​depending on the number of proxies.

Also remember that you can be NATed ( Network Address Translation ). If your ip is internal (10.xxx or 192.168.xx to name a few), you are definitely behind a NAT router and only your external ip will be exposed to websites.

Here is a small C # snippet that shows the definition of the client ip, the logic converts python easily, and the server headers are the same:

string clientIp = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if( !string.IsNullOrEmpty(clientIp) ) {
    string[] forwardedIps = clientIp.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries );
    clientIp = forwardedIps[forwardedIps.Length - 1];
} else {
    clientIp = context.Request.ServerVariables["REMOTE_ADDR"];
}

      

+4


a source







All Articles