How to get IP address of the server that HttpWebRe

2019-02-17 02:28发布

DSN can return multiple IP addresses so rather then using DNS resolving to get the IP address after my request I want to get the IP that my HttpWebRequest connected to.

Is there anyway to do this in .NET 3.5?

For example when I do a simple web request to www.microsoft.com I want to learn that which IP address it connected to send the HTTP request, I want to this programmatically (not via Wireshark etc.)

2条回答
太酷不给撩
2楼-- · 2019-02-17 03:09

This is a working example:

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());
    }
}
查看更多
家丑人穷心不美
3楼-- · 2019-02-17 03:17

here you go

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

Use remoteEndPoint to collect the data you want.

查看更多
登录 后发表回答