[英]Sending HttpWebRequest through a specific network adapter
我有兩個無線網絡適配器連接到我的計算機,每個都連接到不同的網絡。 我想構建一種代理服務器,我的瀏覽器將連接到它,它將從不同的適配器發送 HTTP 請求,因此網頁上的加載時間會更短。 你們知道如何決定從哪個網絡適配器發送 HttpWebRequest 嗎?
謝謝:)
更新
我使用了這段代碼:
public static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
List<IPEndPoint> ipep = new List<IPEndPoint>();
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();
}
但是,即使更改了我從 WhatIsMyIp 獲得的 IP 發送的 IPEndPoint 仍然是一樣的.. 有什么幫助嗎?
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);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.