如何获取HttpWebRequest连接的服务器的IP地址?

时间:2011-07-11 19:53:59

标签: .net httpwebrequest dns ip

DSN可以返回多个IP地址,而不是在我的请求之后使用DNS解析来获取IP地址我希望得到我的HttpWebRequest连接到的IP。

无论如何在.NET 3.5中都这样做吗?

例如,当我向www.microsoft.com做一个简单的Web请求时,我想知道它连接的IP地址发送HTTP请求,我想以编程方式(不通过Wireshark等。

2 个答案:

答案 0 :(得分: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 :(得分:3)

这是一个有效的例子:

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