如何在HttpWebRequest中更改原始IP

Tud*_*ean 15 c# ip webrequest httpwebrequest

我在已分配5个IP的服务器上运行此应用程序.我使用HttpWebRequest从网站获取一些数据.但是当我建立连接时,我能够指定连接的5个IP中的哪一个.HttpWebRequest是否支持此功能?如果不能,我可以从中继承一个类来改变它的行为吗?我在这里需要这样的想法.

我的代码现在是这样的:

System.Net.WebRequest request = System.Net.WebRequest.Create(link);
((HttpWebRequest)request).Referer = "http://application.com";
using (System.Net.WebResponse response = request.GetResponse())
{
    StreamReader sr = new StreamReader(response.GetResponseStream());
    return sr.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*ron 26

根据这个,没有.您可能需要使用套接字,我知道您可以选择本地IP.

编辑:实际上,它似乎有可能.HttpWebRequest有一个ServicePoint属性,后者又有BindIPEndPointDelegate,可能就是你要找的东西.

给我一点,我要举起一个例子......

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com");

req.ServicePoint.BindIPEndPointDelegate = delegate(
    ServicePoint servicePoint,
    IPEndPoint remoteEndPoint,
    int retryCount) {

    if (remoteEndPoint.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) {
        return new IPEndPoint(IPAddress.IPv6Any, 0);
    } else {
        return new IPEndPoint(IPAddress.Any, 0);
    }

};

Console.WriteLine(req.GetResponse().ResponseUri);
Run Code Online (Sandbox Code Playgroud)

基本上,代表必须返回IPEndPoint.你可以选择你想要的任何东西,但是如果它不能绑定到它,它将再次调用委托,最多为int.MAX_VALUE次.这就是为什么我包含代码来处理IPv6,因为IPAddress.Any是IPv4.

如果你不关心IPv6,你可以摆脱它.另外,我将实际选择的IPAddress作为练习留给读者:)

  • 英国开发商,你不能随意挑选任何IP。它必须是连接到您的计算机的适配器的 IP 地址。如果你一直选择一个它无法绑定的IP地址,那么它会继续调用委托。解决方案是使用 IPAddress.Any(或 IPV6 等效项),或枚举设备以查找可以使用的设备。(我推荐前者) (2认同)