Have the address of the client in python

情到浓时终转凉″ 提交于 2019-12-13 09:01:23

问题


My request is : I have my web pages created in python (wherein there is html code), each pages has a button to go to the next page. Is it possible to get the address of the client when we submit an html form for example ? I mean, to have into the URL address of the client.

If that possible, I'll show my code, else I delete my question.

that's my html code :

ip = cgi.escape(os.environ["REMOTE_ADDR"])

<html>

path install: ${install_path}<br/><br/>

os: ${os}<br/><br/>

unix user: ${user_name}<br/><br/>

<form name="sd" method="get" action="ip/cgi/scriptGet.py">
    Name: <input type="text" name="name"><br/><br/>
    Pseudo: <input type="text" name="pseudo"/><br/><br/>
    <input type="submit" value="OK"/>
</form>

and here my python code:

import os, sys, platform, getpass, tempfile
import webbrowser
import string
import json
import cgi, cgitb, os   

def main( server_IP,install_path):

  template = open('scriptHmtl.phtml').read()

  contenu = string.Template(template).substitute(
            install_path = install_path,
            os = user_os,
            user_name = user_login
            )

if __name__ == "__main__":
  server_IP = sys.argv[1]
  install_path = sys.argv[2]

main(server_IP,install_path)

回答1:


You can use cgi and REMOTE_ADDR and use like this :

cgi.escape(os.environ["REMOTE_ADDR"])

Put that in a variable and call the variable into action of your html form ....




回答2:


The IP of the client (which I assume is what you mean by "address of the client") is passed to your server at the TCP/IP level. If you are using CGI (which seems to be the case according to some info hidden in your comments and not stated in your question), it should be available to the CGI script environment as REMOTE_ADDR (cf http://www.ietf.org/rfc/rfc3875, section 4.1.8). In Python, the way to access environment variables is to use os.environ (https://docs.python.org/2/library/os.html#os.environ).

Note that since the CGI script will have access to this address, you don't need to add it to the URL, querystring or (in the case of a POST or PUT request) request's body.

Also note that if your server is accessed thru a proxy, load balancer or whatever, the REMOTE_ADDR might not be the real client IP and you may have to check the HTTP request's headers for a X-Forwarded-For header, cf http://en.wikipedia.org/wiki/X-Forwarded-For. This header (if positionned) should be accessible in the same way as REMOTE_ADDR or any other request header, but possibly renamed as HTTP_X_FORWARDED_FOR, cf http://www.ietf.org/rfc/rfc3875.txt sections 4.1 and 4.1.18.



来源:https://stackoverflow.com/questions/24825836/have-the-address-of-the-client-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!