2010-11-25 81 views
12

我有一個多IP地址的服務器。現在我需要使用http協議與幾臺服務器進行通信。每個服務器只接受來自我的服務器的指定IP地址的請求。但是在.NET中使用WebRequest(或HttpWebRequest)時,請求對象會自動選擇一個IP地址。無論如何,我無法找到將請求與地址綁定的地方。我可以使用.NET Framework從指定的IP地址發送webrequest嗎?

有無論如何這樣做嗎?或者我必須自己實施一個webrequest課程?

回答

12

您需要使用ServicePoint.BindIPEndPointDelegate回調。

http://blogs.msdn.com/b/malarch/archive/2005/09/13/466664.aspx

之前與HttpWebRequest的相關聯的套接字嘗試連接到遠程端的委託被調用。

public static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount) 
{ 
    Console.WriteLine("BindIPEndpoint called"); 
     return new IPEndPoint(IPAddress.Any,5000); 

} 

public static void Main() 
{ 

    HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://MyServer"); 

    request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback); 

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

} 
+1

令人驚歎。問題就這樣簡單地解決了!謝謝,山姆。 – 2010-11-25 11:25:46

6

如果你想做到這一點使用WebClient你需要它的子類:

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

和子類:

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; 
    } 
} 

(感謝@Samuel爲全重要的ServicePoint.BindIPEndPointDelegate部分)

相關問題