Binding an IP address just works for the first time

后端 未结 4 879
天涯浪人
天涯浪人 2021-01-11 16:02

I want to make a web request from one of available IP addresses on server so I use this class:

public class UseIP
{
    public string IP { get; private set;          


        
4条回答
  •  自闭症患者
    2021-01-11 16:46

    I have changed your example a little and make it work on my machine:

    public HttpWebRequest CreateWebRequest(Uri uri)
    {
        HttpWebRequest wr = WebRequest.Create(uri) as HttpWebRequest;
        wr.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(Bind);
        return wr;
    }
    

    I did that because:

    • I think the call to FindServicePoint actually does the request using the "default" ip, without even calling the binding delegate, to the URI you have specified. In my machine, at least, the BindIPEndPointDelegate was not called in the way you have presented (I know the request was made because I didn't set the Proxy and got a proxy authentication error);
    • In the documentation of ServicePointManager, it states that "If there is an existing ServicePoint object for that host and scheme, the ServicePointManager object returns the existing ServicePoint object; otherwise, the ServicePointManager object creates a new ServicePoint object" witch would probably return always the same ServicePoint if the URI was the same (maybe explaining why the subsequent calls is happening in the same EndPoint).
    • In this way we can be sure that, even when the URI has already been requested, it will use the desired IP instead of using some previous "caching" of ServicePointManager.

提交回复
热议问题