问题
I am writing a web server script and need remote port from which a client connected. Is there any way I may retrieve it? I am using django framework for development.
ADDED:
When a client sends a HTTP Request, there would be one source TCP port at the machine, which would be modified in NAT process. Finally, SYN (TCP) to web server would be from, say port P1. I need that port P1 from which the web server receives a connection request.
Now in HttpRequest meta dict, I was not able to see it. Is there any other way?
回答1:
The destination (server) port is included in the request's meta dictionary.
def get_port(request):
if 'SERVER_PORT' in request.META:
return request.META['SERVER_PORT']
else:
return None
The source port will not be accessible at the application layer of the TCP/IP stack.
回答2:
This does not seem possible with only Django, however if you run it on top of Apache and mod_wsgi you can then access it from a request object by request.META['REMOTE_PORT']
https://github.com/GrahamDumpleton/mod_wsgi
回答3:
I also proposed the similiar question with no satisfying answers. Finally, after days of struggling, I answer it, with a working, but ugly Solution on 'how to get client port in Django'. Anyone see this please help me to improve this method.
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.
来源:https://stackoverflow.com/questions/20316078/how-to-retrieve-remote-port-in-django