查找失败的HttpWebRequest中使用的IP地址

时间:2019-04-01 00:30:18

标签: .net

我的环境中DNS名称可能会解析为我无法控制的其他IP地址; IP地址也可能会更改,并被外部防火墙阻止。 我可以通过这种方式记录用于连接的IP地址:

public static IPEndPoint BindIPEndPoint1(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
        { 
            Console.Write($"IP address = {remoteEndPoint.ToString()}");
            return null;
        }

            try
            {
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request = (HttpWebRequest)WebRequest.Create(url);
                request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPoint1);
                request.Proxy = new WebProxy();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                stop.Stop();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine($"OK in {stop.ElapsedMilliseconds} ms");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"{response.StatusCode} in {stop.ElapsedMilliseconds} ms");
                }
            }
            catch (System.Net.WebException exs)
            {
                stop.Stop();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"{exs.Message} in {stop.ElapsedMilliseconds} ms");
            }

显示成功连接的IP地址;但是,如果System.Net.WebException失败,则显示为“ Timed Out”(超时)。还有其他方法可以在程序中标识这些失败请求中URL解析为哪个IP地址。 执行DNS查找不适合,因为它可能与导致失败的确切请求不匹配。 此外,按地址访问该站点不起作用,因为该站点要求通过主机名进行访问。

1 个答案:

答案 0 :(得分:0)

该问题与HttpWebRequest的范围有关。在try块之外创建HttpWebRequest可以处理失败的请求。

HttpWebRequest request;
                request = (HttpWebRequest)WebRequest.Create(url);
                request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPoint1);

                try
                {
                    request.Proxy = new WebProxy();
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    stop.Stop();
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine($"OK in {stop.ElapsedMilliseconds} ms");
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine($"{response.StatusCode} in {stop.ElapsedMilliseconds} ms");
                    }
                }
                catch (System.Net.WebException exs)
                {
                    stop.Stop();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"{exs.Message} in {stop.ElapsedMilliseconds} ms");
                }