How do I get the client Remote Port number in a Django?

I know I can use request.META[‘REMOTE_ADDR’] to get the client’s IP in my django view function.
However, I have no idea how to get the client remote port number.

For example, you can see your own remote port number on the site below:

https://www.myip.com/

MY VIEW PY:

if request.user.is_authenticated:

        gelenIleti = request.META.get('HTTP_X_FORWARDED_FOR')

        if gelenIleti:

            ip = gelenIleti.split(',')[0]

        else:

            ip = request.META.get('REMOTE_ADDR')

            portNumarasi = request.META['SERVER_PORT']

        logger.info(' ' + 'LOG KAYDI :' + ' ' + ' KULLANICI : ' + request.user.username + ' ' + ' IP : ' + ip + ' ' + ' SERVER PORT : ' + portNumarasi)

UPDATE: (SOLVED)

I solved the problem by this way;

sock = request._stream.stream.stream.raw._sock client
ip, port = sock.getpeername()

The originating IP is not part of the http protocol - it’s something being added by uwsgi. Since I cannot find anything in the uwsgi protocol allowing for the originating port to be supplied, I’m guessing it’s not going to be available to you.
That some other utility is showing it to you indicates that whatever they’re using has access to the lower-level socket directly and isn’t working through one of the standard web servers such as nginx.
(I am curious to understand what possible value it may be given that it’s not necessarily going to reflect the actual port used by the originating device.)

To add to Ken’s comment, if you’re using Channels the REMOTE_PORT is exposed as a part of the ASGI handler in Django.

1 Like