HttpWebRequest指定IP请求


一个服务器上配置多个外网IP ,HttpWebRequest实现指定IP的域名请求(也可以考虑使用代理实现)

需要使用HttpWebRequest的ServicePoint.BindIPEndPointDelegate代理实现
注:(如果IP指定错误,服务器好像会使用默认最优先IP请求)
    /// <summary>
    /// 通过设置这个属性,可以在发出连接的时候绑定客户端发出连接所使用的IP地址。 
    /// </summary>
    /// <param name="servicePoint"></param>
    /// <param name="remoteEndPoint"></param>
    /// <param name="retryCount"></param>
    /// <returns></returns>
    public static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
    {
        return new IPEndPoint(IPAddress.Parse("192.168.1.1"), 0);//端口号
    }
    /// <summary>
    /// 一个服务器上面配置多个IP 固定出网IP
    /// </summary>
    public static void MakeRequest()
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.baidu.com");
        //设置本地的出口ip和端口
        request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);
        if (ServicePointManager.DefaultConnectionLimit < 10)
        {
            ServicePointManager.DefaultConnectionLimit = 10;
        }
        //req.ServicePoint.ConnectionLimit=int.Max;  //允许最大连接数 

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        response.ToString();
    }

 

也可以直接写成

        request.ServicePoint.BindIPEndPointDelegate = delegate
        {
            return new IPEndPoint(IPAddress.Parse(ip), 0);
        };

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM