Can I send webrequest from specified ip address with .NET Framework?

后端 未结 3 1626
清歌不尽
清歌不尽 2020-12-05 05:58

I have a server with multi ip addresses. Now I need to communicate with several servers with http protocol. Each server only accept the request from a specified ip address o

3条回答
  •  一向
    一向 (楼主)
    2020-12-05 06:27

    If you want to do this using WebClient you'll need to subclass it:

    var webClient = new WebClient2(IPAddress.Parse("10.0.0.2"));
    

    and the subclass:

    public class WebClient2 : WebClient
    {
        public WebClient2(IPAddress ipAddress) {
            _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;
        }
    }
    

    (thanks @Samuel for the all important ServicePoint.BindIPEndPointDelegate part)

提交回复
热议问题