Detect remote port in IHttpHandler

238 views Asked by At

Hey how do you get the remote port for a request on the web server?

So my code should look like this:

public class EndpointReflectionHandler : IHttpHandler
{
    public new void ProcessRequest(HttpContext context)
    {
        string address = context.Request.UserHostAddress;
        int port = context.Request.UserHostPort;            //it's not there

        context.Response.ContentType = "text/plain";
        context.Response.Write(address + ":" + port);
    }
}

..but I can't find anything to get the port.

EDIT. Thanks to Tim for great comment:

Here's the full workflow:

  1. Client starts, opens a socket
  2. Hey webservice what's my IP and port?
  3. It's 1.2.3.4:1234
  4. Hey other person, I'll listen on 1.2.3.4:1234 (even though to me it looks like 9.9.9.9:9999
  5. OK man I'll connect to 1.2.3.4:1234
  6. Everyone happy, have a beer
2

There are 2 answers

1
Andy On

I got it context.Request.ServerVariables["REMOTE_PORT"].

There's nothing about it, just guesswork and looking everywhere :)

0
mggSoft On

You can get the port with this line:

int port = new Uri(request.UserHostAddress).Port;