views:

42

answers:

3

Say, I have 2 or more active network cards on my machine. i am using a c# application from which i am calling an asynchronous service. i want to be able to determine which ipaddress have i used when calling this service.

for example, my two active ip's are 192.168.10.5 and 192.168.5.7 and the service ipaddress is 192.168.7.12.

A: 

You can try this:

public static string GetExternalIP()
{
    try
    {
        using (WebClient client = new WebClient())
        {
             string ip = client.DownloadString("http://whatismyip.com/automation/n09230945.asp");
             return ip;
        }
    }
    catch (Exception) { return null; }
}

Code slightly reworked from http://goo.gl/QF97

tishon
A: 

See this other SO question

Timores
A: 

Hmm. I don't think there's a managed solution. GetBestInterface and/or GetBestRoute would seem to be the right places to start in the WIn32 API (probably GetBestRoute, by my reading of it).

Also, due to the vagaries of this wonderful thing that is the internet, and dynamic routing, by the time you've worked out the answer, it may have changed.

It may be best to provide the service with a list of IP addresses, and let it use whichever one works.

Edit

Or you may be able to use WCF callbacks, and make WCF do most of the hard work (I've not spent a lot of time in WCF itself, not sure how much work it would do for you here)

Damien_The_Unbeliever