问题
I am using django to build my web server, other people connect to me as clients. Now I need to know the clients' port number to distinguish them. If their browser opens two 'Tabs' of the same link, i.e. two pages but the same link, I also have to distinguish them.
Although I know I can use request.META['REMOTE_ADDR'] to get the client's IP in my django view function, but this realy is not enough for me.
Then I studied some TCP/IP basics and then I know that in TCP/IP layer, every IP packet has an IP header which contains the client's port number. But how can I access it in django?
Additional info:
- I'm using python 2.6 and django 1.4
- I know every TAB of a browser will be allocated a random unique port to access my django web page port. -- see this link 'The web server opens port 80, but the browser has a different, randomly-assigned port.' I really need to distinguish them. So my intuitive thoughts is to use the port number in the IP packet. If you have any other suggestion, also welcome.
- I have found the similar question here, but I am not using Apache now. And this may be hard for me to config so maybe causing other more complex questions. This might make this simple question complex.
回答1:
- Your assumption about 'every user connection opens connection at unique port' is wrong. All users are using the same port to connect.
- To distinguish users Django (and almost every other frameworks) is using sessions. Every user gets a cookie with his unique session ID, and this cookie is passed to a server on every connection, so the application can distinguish users.
Here is documentation on sessions:
https://docs.djangoproject.com/en/1.8/topics/http/sessions/
回答2:
Yes, after days of struggling, I answer it, with a working, but ugly solution on 'how to get client port in Django'.
in your python26/Lib/SocketServer.py, find
def process_request_thread
,addglobal gClientPort; gClientPort = client_address
use this global value in yout project. Its format is ('12.34.56.78',55437) for example. 55437 is the port number.
回答3:
while I debug the django , I find this
request.environ["wsgi.input"].raw._sock.getpeername()
maybe it can work
来源:https://stackoverflow.com/questions/30262193/how-do-i-get-the-client-port-number-in-a-django-project