一個服務器上配置多個外網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); };