我可以使用.NET Framework从指定的IP地址发送webrequest吗?

时间:2010-11-25 03:18:22

标签: c# .net ip-address webrequest

我有一个多IP地址的服务器。现在我需要使用http协议与多个服务器通信。每个服务器只接受来自我的服务器的指定IP地址的请求。但是在.NET中使用WebRequest(或HttpWebRequest)时,请求对象将自动选择IP地址。我无论如何都找不到用地址绑定请求。

有没有这样做?或者我必须自己实施webrequest课程?

3 个答案:

答案 0 :(得分:14)

您需要使用ServicePoint.BindIPEndPointDelegate回调。

http://blogs.msdn.com/b/malarch/archive/2005/09/13/466664.aspx

  

在与httpwebrequest关联的套接字尝试连接到远程端之前调用委托。

public static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
    Console.WriteLine("BindIPEndpoint called");
      return new IPEndPoint(IPAddress.Any,5000);

}

public static void Main()
{

    HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://MyServer");

    request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

}

答案 1 :(得分:6)

如果您想使用WebClient执行此操作,则需要对其进行子类化:

var webClient = new WebClient2(IPAddress.Parse("10.0.0.2"));

和子类:

public class WebClient2 : WebClient
{
    public WebClient2(IPAddress ipAddress) {
        _ipAddress = ipAddress;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = (WebRequest)base.GetWebRequest(address);

        ((HttpWebRequest)request).ServicePoint.BindIPEndPointDelegate += (servicePoint, remoteEndPoint, retryCount) => {

            return new IPEndPoint(_ipAddress, 0);
        };

        return request;
    }
}

(感谢@Samuel所有重要的ServicePoint.BindIPEndPointDelegate部分)

答案 2 :(得分:2)

不确定您是否阅读过这篇文章(?)

How to specify server IP in HttpWebRequest

Specifying Source IP of HttpWebRequest