通过特定的网络适配器发送HttpWebRequest

我有两个连接到我的计算机的无线网络适配器,每个都连接到不同的网络。 我想构建一种我的浏览器将连接到的代理服务器,它将从不同的适配器发送每个HTTP请求,因此网页上的加载时间会更短。 你们知道我怎么决定从哪个网络适配器发送HttpWebRequest?

谢谢 :)

UPDATE

我用过这段代码:

public static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount) { List ipep = new List(); foreach (var i in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()) { foreach (var ua in i.GetIPProperties().UnicastAddresses) ipep.Add(new IPEndPoint(ua.Address, 0)); } return new IPEndPoint(ipep[1].Address, ipep[1].Port); } private void button1_Click(object sender, EventArgs e) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://whatismyip.com"); request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream()); string x = sr.ReadToEnd(); } 

但即使改变IPEndPoint我发送的IP我从WhatIsMyIp得到的仍然是相同的..任何帮助?

BindIPEndPointDelegate可能就是你在这里所追求的。 它允许您强制将特定的本地IP作为发送HttpWebRequest的终点。

这个例子对我有用:

 using System; using System.Net; class Program { public static void Main () { foreach (var ip in Dns.GetHostAddresses (Dns.GetHostName ())) { Console.WriteLine ("Request from: " + ip); var request = (HttpWebRequest)HttpWebRequest.Create ("http://ns1.vianett.no/"); request.ServicePoint.BindIPEndPointDelegate = delegate { return new IPEndPoint (ip, 0); }; var response = (HttpWebResponse)request.GetResponse (); Console.WriteLine ("Actual IP: " + response.GetResponseHeader ("X-YourIP")); response.Close (); } } } 

这是因为WebRequest使用ServicePointManager并且它缓存用于单个URI的实际ServicePoint。 因此,在您的情况下,BindIPEndPointDelegate只调用一次,所有后续CreateRequest重用相同的绑定接口。 这是一个更低级别的示例,其中TcpClient实际上有效:

  foreach (var iface in NetworkInterface.GetAllNetworkInterfaces()) { if (iface.OperationalStatus == OperationalStatus.Up && iface.NetworkInterfaceType != NetworkInterfaceType.Loopback) { Console.WriteLine("Interface: {0}\t{1}\t{2}", iface.Name, iface.NetworkInterfaceType, iface.OperationalStatus); foreach (var ua in iface.GetIPProperties().UnicastAddresses) { Console.WriteLine("Address: " + ua.Address); try { using (var client = new TcpClient(new IPEndPoint(ua.Address, 0))) { client.Connect("ns1.vianett.no", 80); var buf = Encoding.UTF8.GetBytes("GET / HTTP/1.1\r\nConnection: close\r\nHost: ns1.vianett.no\r\n\r\n"); client.GetStream().Write(buf, 0, buf.Length); var sr = new StreamReader(client.GetStream()); var all = sr.ReadToEnd(); var match = Regex.Match(all, "(?mi)^X-YourIP: (?'a'.+)$"); Console.WriteLine("Your address is " + (match.Success ? match.Groups["a"].Value : all)); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }