3

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?

Confused
  • 617
  • 1
  • 9
  • 17
  • 1
    It's unclear what you are asking. The port should always be the same, namely `80` because that's the default port for `http` requests. There is also `443` for `https`. You should read this: https://docs.djangoproject.com/en/dev/ref/request-response/ – Alp Dec 01 '13 at 19:18
  • While 80/443 are the standard ports used for public facing websites, there are times where they will not be used. A couple of cases that immediately come to mind are in a development environment or setting up a web server in a non-business environment where port 80 is blocked by your ISP (i.e. Cox). – Joseph Paetz Dec 01 '13 at 22:15
  • I wish to know the port on client side (probably the port of gateway on client network side) which sent the HTTP Request. – Confused Dec 02 '13 at 07:14

2 Answers2

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.

Joseph Paetz
  • 876
  • 1
  • 7
  • 12
  • Correct me if i am wrong, but i think you can always find __SERVER_PORT__ value in __request.META__. right? – alioguzhan Dec 01 '13 at 22:27
  • @alix To be honest, I am not sure if it is guaranteed or not. If you are correct, then the conditional statement can be removed, but I tend to err on the side of caution. – Joseph Paetz Dec 01 '13 at 22:34
  • Got it. I am not sure 100% too. thats why i said 'correct me if am wrong'. If i figure it out, gonna tell you :) – alioguzhan Dec 01 '13 at 22:37
  • I wish to know the port on client side (probably the port of gateway on client network side) which sent the HTTP Request. – Confused Dec 02 '13 at 07:14
  • When a client connects to a server it specifies the destination port. The destination port is the port the server is running, while the source port is the port the client opens (if behind a NAT then that corresponding port) @Rajat wishes to know this port. – wi1 Apr 20 '15 at 02:13
1

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

wi1
  • 486
  • 3
  • 14