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.

Erigami
  • 804
  • 1
  • 8
  • 20

1 Answers1

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!

Marcel N.
  • 13,726
  • 5
  • 47
  • 72
  • I'm always up for a little programmer fun, but reflecting that deeply feels a little dirty. :) – Erigami Jun 26 '12 at 17:24
  • @Erigam: Of course it's dirty, no argue with that. I already mentioned that this is not to be used in production. – Marcel N. Jun 26 '12 at 17:25
  • @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. – Despertar Jul 30 '12 at 07:14