How do I get the local port number of an HttpWebRequest?
Asked Answered
R

1

4

I'm making a long-running request with an HttpWebRequest asynchronously. While the request is running, I'd like to be able to get the local port of the request (ie, the one on the client, not the server). How do I do that?

I've looked at HttpWebRequest.ServicePoint.BindIPEndPointDelegate, but that just seems to allow the caller to specify the local addy/port. Ideally, I'd like to allow HttpWebRequest to pick its local port normally and then ask it what it chose.

Racklin answered 26/6, 2012 at 16:36 Comment(4)
Just curious why you want to know this.Ambrotype
I'm abusing HTTP to create a notification mechanism. I want to know the port so that other streams can tell the server which notification channel is theirs.Racklin
But have you considered other over-HTTP mechanisms? Such as WCF. What is on the other end of your HttpWebRequest?Rigatoni
I'm working with an existing app that doesn't provide a WCF interface.Racklin
R
0

Unfortunately, the HttpWebRequest class really does not expose what you are asking for.

I don't recommend what I'll say below to be used in production. It's just programmer fun.

The ServicePoint class has a private NetworkStream member called m_NetworkStream, exposed through internal property NetworkStream.

As you may already know, NetworkStream already exposes a public Socket property which gives you the underlying socket, from which you can access the local IP endpoint.

So the only challenge is to obtain the PropertyInfo for ServicePoint.NetworkStream, get its value for a specific HttpWebRequest instance and from there on it's a straight line.

Note: For a proper solution you may want to take a look at Windows HTTP Services and then perhaps create a managed wrapper around it (if there isn't one already).

Enjoy!

Rigatoni answered 26/6, 2012 at 17:12 Comment(3)
I'm always up for a little programmer fun, but reflecting that deeply feels a little dirty. :)Racklin
@Erigam: Of course it's dirty, no argue with that. I already mentioned that this is not to be used in production.Rigatoni
@MarcelNita Enumerating through the properties of ServicePoint I do not see the NetworkStream property you are talking about. I have BindingFlags.Instance | BindingFlags.NonPublic set.Quincyquindecagon

© 2022 - 2024 — McMap. All rights reserved.