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

白昼怎懂夜的黑 提交于 2019-12-22 09:31:29

问题


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.


回答1:


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!



来源:https://stackoverflow.com/questions/11211974/how-do-i-get-the-local-port-number-of-an-httpwebrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!