How to get IP address of the server that HttpWebRequest connected to?

后端 未结 2 679
青春惊慌失措
青春惊慌失措 2020-12-19 05:23

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.

相关标签:
2条回答
  • 2020-12-19 05:51

    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.

    0 讨论(0)
  • 2020-12-19 05:53

    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());
        }
    }
    
    0 讨论(0)
提交回复
热议问题