问题
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