2011-07-11 152 views
7

DSN可以返回多個IP地址,而不是使用DNS解析來獲取我的請求後的IP地址我想獲取我的HttpWebRequest連接到的IP。如何獲取HttpWebRequest連接的服務器的IP地址?

無論如何要在.NET 3.5中做到這一點?

例如,當我做一個簡單的Web請求訪問www.microsoft.com我想得知其IP地址,連接發送HTTP請求,我想這個編程(不通過的Wireshark等

回答

4

在這裏你去

static void Main(string[] args) 
     { 
      HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com"); 
      req.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPoint1); 

      Console.ReadKey(); 
     } 

     public static IPEndPoint BindIPEndPoint1(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount) 
     { 
      string IP = remoteEndPoint.ToString(); 
      return remoteEndPoint; 
     } 

使用remoteEndPoint收集所需的數據。

+1

有什麼理由建立一個WebProxy? –

+0

其次不會返回remoteEndPoint會失敗嗎?當我讀取BindIPEndPointDelegate用於綁定本地IP地址時,如果返回remoteEndPoint,它將失敗(或類似的東西),因爲它無法綁定它。我假設返回這應該修復它,雖然:新IPEndPoint(IPAddress.Any,0) –

+1

我已經嘗試過,但BindIPEndPoint1方法永遠不會被調用。 – user626528

2

這是一個工作示例:

using System; 
using System.Net; 

class Program 
{ 
    public static void Main() 
    { 
     IPEndPoint remoteEP = null; 
     HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com"); 
     req.ServicePoint.BindIPEndPointDelegate = delegate (ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount) { 
      remoteEP = remoteEndPoint; 
      return null; 
     }; 
     req.GetResponse(); 
     Console.WriteLine (remoteEP.Address.ToString()); 
    } 
} 
相關問題