ServicePoint.BindIPEndPointDelegate不起作用

时间:2015-11-17 06:09:57

标签: c# httpwebrequest

在我的c#程序中,我需要通过指定的ip连接到一个网站。因为我使用 ServicePoint.BindIPEndPointDelegate ,但它不起作用。我搜索并发现了这个:

服务器支持ipv6时,我们尝试使用其ipv6地址与服务器建立连接。但是回调中指定了ipv4地址。由于在调用委托时已使用AddressFamily.InterNetworkv6创建套接字,因此绑定到IPv4地址失败。所以代表再次被召唤。但返回相同的端点,因此绑定再次失败。这会重复Integer.MaxValue次,然后抛出OverflowException。注意Integer.MaxValue是一个非常大的值,看起来好像代码已经进入无限循环。

现在我该如何解决这个问题?我需要连接指定的ip。 代码:

 private void button1_Click(object sender, EventArgs e)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.scopus.com");

        request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream data = response.GetResponseStream();
        StreamReader reader = new StreamReader(data);
        var result = reader.ReadToEnd();

        reader.Close();
        response.Close();
        txtResult.Text = result;
    }

    public static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
    {

        IPAddress address=IPAddress.Parse("77.81.99.66");
        if (retryCount == 5)
            return null;
        return new IPEndPoint(address, 7070);

    }

0 个答案:

没有答案
相关问题