陋室铭
永远也不要停下学习的脚步(大道至简至易)

需要定义一个类,重写GetWebRequest,在方法内,指定IP地址

 

复制代码
    public class MyWebClient : WebClient
    {
        private IPAddress ipAddress;

        public MyWebClient(IPAddress ipAddress)
        {
            this.ipAddress = ipAddress;
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = (WebRequest)base.GetWebRequest(address);

            ((HttpWebRequest)request).ServicePoint.BindIPEndPointDelegate += (servicePoint, remoteEndPoint, retryCount) =>
            {
                return new IPEndPoint(ipAddress, 0);
            };

            return request;
        }
    }
复制代码

 

使用时,  在实例化构造函数中传入所需IP即可

posted on 2019-06-11 16:20  宏宇  阅读(1470)  评论(0编辑  收藏  举报