Ephi
Ephi

Reputation: 121

Sending HttpWebRequest through a specific network adapter

A couple of days ago I asked a question about sending HttpWebRequest through a specific network adapter and someone told me to use BindIPEndPointCallback. I tried this:

public static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
    List<IPEndPoint> ipep = new List<IPEndPoint>();
    foreach (var i in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
    {
        foreach (var ua in i.GetIPProperties().UnicastAddresses)
            ipep.Add(new IPEndPoint(ua.Address, 0));
    }
    return new IPEndPoint(ipep[1].Address, ipep[1].Port);
}

private void button1_Click(object sender, EventArgs e)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://whatismyip.com");
    request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader sr = new StreamReader(response.GetResponseStream());
    string x = sr.ReadToEnd();
}

But it still doesn't work. It sends the HttpWebRequest through the same network adapter. Is there anything else I could try?

Upvotes: 1

Views: 1457

Answers (2)

moander
moander

Reputation: 2188

If your local end point is a private ip address (192.168.50.103 is), your router will translate that address to a different public ip, and this is the address whatsmyip can see.

I suggest your try this example:

using System;
using System.Net;

class Program
{
    public static void Main ()
    {
        // TODO: Put your ip addresses in this list
        var ips = new IPAddress[]
        {
            IPAddress.Parse("10.0.0.3"),
            IPAddress.Parse("192.168.1.7")
        };

        foreach (var ip in ips)
        {
            try
            {
                Console.WriteLine("Request from: " + ip);
                var request = (HttpWebRequest)HttpWebRequest.Create("http://ns1.vianett.no/");
                request.ServicePoint.BindIPEndPointDelegate = delegate
                {
                    return new IPEndPoint(ip, 0);
                };
                var response = (HttpWebResponse)request.GetResponse();
                Console.WriteLine("Actual IP: " + response.GetResponseHeader("X-YourIP"));
                response.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

Upvotes: 1

feroze
feroze

Reputation: 7594

What you are trying to do may or may not be supported by the underlying platform.

Google for "Strong/Weak host models".

For eg, this is a good introduction to the topic:

http://technet.microsoft.com/en-us/library/2007.09.cableguy.aspx

Upvotes: 0

Related Questions