如何更改 HttpWebRequest 中的原始 IP
我在分配了 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();
}
I'm running this application on a server that has assigned 5 IPs. I use HttpWebRequest to fetch some data from a website. But when I make the connection I have be able to specify which one of the 5 IPs to make the connection from. Does HttpWebRequest support this? If it doesn't can I inherit a class from it to change it's behavior? I need so ideas here.
My code right now is something like:
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据这个,没有。你可能必须下拉到使用套接字,我知道你可以选择本地IP。
编辑:实际上,这似乎是可能的。 HttpWebRequest 有一个 ServicePoint 属性,该属性又具有 BindIPEndPointDelegate,这可能就是您正在寻找的。
请给我一点时间,我将举一个例子...
基本上,委托必须返回一个 IPEndPoint。您可以选择任何您想要的内容,但如果它无法绑定到它,它将再次调用委托,最多 int.MAX_VALUE 次。这就是为什么我包含了处理 IPv6 的代码,因为 IPAddress.Any 是 IPv4。
如果你不关心 IPv6,你可以摆脱它。另外,我将实际选择 IP 地址作为练习留给读者:)
According to this, no. You may have to drop down to using Sockets, where I know you can choose the local IP.
EDIT: actually, it seems that it may be possible. HttpWebRequest has a ServicePoint Property, which in turn has BindIPEndPointDelegate, which may be what you're looking for.
Give me a minute, I'm going to whip up an example...
Basically, the delegate has to return an IPEndPoint. You can pick whatever you want, but if it can't bind to it, it'll call the delegate again, up to int.MAX_VALUE times. That's why I included code to handle IPv6, since IPAddress.Any is IPv4.
If you don't care about IPv6, you can get rid of that. Also, I leave the actual choosing of the IPAddress as an exercise to the reader :)
试试这个:
然后尝试将 ConnectionGroupName 设置为您希望使用的每个源 IP 的不同名称。
编辑:将其与上面答案中的 IP 绑定委托结合使用。
Try this:
Then try setting the ConnectionGroupName to something distinct per source ip you wish to use.
edit: use this in conjunction with the IP binding delegate from the answer above.