如何强制ipv6或ipv4用于HttpWebRequest或WebRequest C#

时间:2016-05-23 07:26:31

标签: c# network-programming ipv6 ipv4

来自node.js我可以这样做告诉node.js使用ipv6 vs ipv4发出请求

static void Main(string[] args)
{
        int i;
        Console.Write("Enter a Number : ");
        i = int.Parse(Console.ReadLine());

        if (i % 2 == 0)
        {
            Console.Write("Entered Number is an Even Number");
            Console.Read();
        }
        else
        {
            Console.Write("Entered Number is an Odd Number");
            Console.Read();
        }
}

var http = require("http"); var options = { hostname: "google.com", family: 4, // set to 6 for ipv6 }; var req = http.request(options, function(res) { .. handle result here .. }); req.write(""); req.end(); 设置为family强制ipv4,将其设置为4强制ipv6。不设置它可以让你工作。

如何在C#(.NET 3.5)中执行相同的操作

我可以想到一种方法是自己为A或AAAA记录发出DNS请求,发出直接IP请求并设置6标头。还有更好的方法吗?

1 个答案:

答案 0 :(得分:4)

您可以使用ServicePoint.BindIPEndPointDelegate

var req = HttpWebRequest.Create(url) as HttpWebRequest;

req.ServicePoint.BindIPEndPointDelegate = (servicePount, remoteEndPoint, retryCount) =>
{
    if (remoteEndPoint.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
    {
        return new IPEndPoint(IPAddress.IPv6Any, 0);
    }

    throw new InvalidOperationException("no IPv6 address");
};