加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 可以使用.NET Framework从指定的ip地址发送webrequest吗?

发布时间:2020-12-15 06:54:51 所属栏目:百科 来源:网络整理
导读:我有一个服务器与多个IP地址.现在我需要与几个服务器通信http协议.每个服务器只接受来自我服务器的指定ip地址的请求.但是当在.NET中使用WebRequest(或HttpWebRequest)时,请求对象将自动选择一个IP地址.我找不到要用地址绑定请求. 有没有这样做?或者我必须自
我有一个服务器与多个IP地址.现在我需要与几个服务器通信http协议.每个服务器只接受来自我服务器的指定ip地址的请求.但是当在.NET中使用WebRequest(或HttpWebRequest)时,请求对象将自动选择一个IP地址.我找不到要用地址绑定请求.

有没有这样做?或者我必须自己实现一个webrequest类?

解决方法

您需要使用ServicePoint.BindIPEndPointDelegate回调.

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

The delegate is called before the socket associated with the httpwebrequest attempts to connect to the remote end.

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

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读