簡體   English   中英

通過特定的網絡適配器發送 HttpWebRequest

[英]Sending HttpWebRequest through a specific network adapter

幾天前,我問了一個關於通過特定網絡適配器發送HttpWebRequest問題,有人告訴我使用BindIPEndPointCallback 我試過這個:

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();
}

但它仍然不起作用。 它通過同一個網絡適配器發送HttpWebRequest 還有什么我可以嘗試的嗎?

如果您的本地端點是私有 ip 地址(192.168.50.103 是),您的路由器將將該地址轉換為不同的公共 ip,這就是 whatsmyip 可以看到的地址。

我建議你試試這個例子:

using System;
using System.Net;

class Program
{
    public static void Main ()
    {
        // TODO: Put your ip addresses in this list
        var ips = new IPAddress[]
        {
            IPAddress.Parse("10.0.0.3"),
            IPAddress.Parse("192.168.1.7")
        };

        foreach (var ip in ips)
        {
            try
            {
                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();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

底層平台可能支持也可能不支持您嘗試做的事情。

谷歌“強/弱主機模型”。

例如,這是對該主題的一個很好的介紹:

http://technet.microsoft.com/en-us/library/2007.09.cableguy.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM