how to change originating IP in HttpWebRequest

前端 未结 2 1331
名媛妹妹
名媛妹妹 2020-11-28 07:36

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 s

相关标签:
2条回答
  • 2020-11-28 08:07

    Try this:

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

    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.

    0 讨论(0)
  • 2020-11-28 08:14

    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...

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

    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 :)

    0 讨论(0)
提交回复
热议问题