【问题标题】:How to get IP address of the server that HttpWebRequest connected to?如何获取 HttpWebRequest 连接的服务器的 IP 地址?
【发布时间】:2011-10-03 02:22:24
【问题描述】:

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

在 .NET 3.5 中是否可以这样做?

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

【问题讨论】:

    标签: .net httpwebrequest dns ip


    【解决方案1】:

    给你

    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 收集你想要的数据。

    【讨论】:

    • 创建 WebProxy 有什么理由吗?
    • 第二次不返回remoteEndPoint会失败?当我读到 BindIPEndPointDelegate 用于绑定本地 IP 地址时,如果您返回 remoteEndPoint,它将失败(或类似的事情),因为它无法绑定它。我认为返回这个应该可以解决它: new IPEndPoint(IPAddress.Any, 0)
    • 我试过这个,但是 BindIPEndPoint1 方法从来没有被调用过。
    【解决方案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());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-07
      • 1970-01-01
      • 2018-08-03
      • 1970-01-01
      相关资源
      最近更新 更多