Imagine a situation, I have PC with two lan cards, one is connected to internet another is connected to local network, how can I detect IP which is connected to internet wi
A hacky way is to fetch and scrape one of the many 'What Is My IP' type websites.
I found a solution:
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
Console.WriteLine(ipProperties.HostName);
foreach (NetworkInterface networkCard in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (GatewayIPAddressInformation gatewayAddr in networkCard.GetIPProperties().GatewayAddresses)
{
Console.WriteLine("Information: ");
Console.WriteLine("Interface type: {0}", networkCard.NetworkInterfaceType.ToString());
Console.WriteLine("Name: {0}", networkCard.Name);
Console.WriteLine("Id: {0}", networkCard.Id);
Console.WriteLine("Description: {0}", networkCard.Description);
Console.WriteLine("Gateway address: {0}", gatewayAddr.Address.ToString());
Console.WriteLine("IP: {0}", System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList[0].ToString());
Console.WriteLine("Speed: {0}", networkCard.Speed);
Console.WriteLine("MAC: {0}", networkCard.GetPhysicalAddress().ToString());
}
}
Use tracert. The first hop should always be on the same subnet as your internet NIC.
example from command prompt.
tracert google.com
the first line is 10.0.0.254 and my nic has the ip of 10.0.2.48. Then it is a simple exercise of parsing the output from tracert.
An alternative solution (that is probably more accurate) is to use the Windows route
command. Here is some code that works for me on Windows Vista:
static string getInternetConnectionIP()
{
using (Process route = new Process())
{
ProcessStartInfo startInfo = route.StartInfo;
startInfo.FileName = "route.exe";
startInfo.Arguments = "print 0.0.0.0";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
route.Start();
using (StreamReader reader = route.StandardOutput)
{
string line;
do
{
line = reader.ReadLine();
} while (!line.StartsWith(" 0.0.0.0"));
// the interface is the fourth entry in the line
return line.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries)[3];
}
}
}
Not 100% accurate (some ISPs don't give you public IP addresses), but you can check if the IP address is on one of the ranges reserved for private addresses. See http://en.wikipedia.org/wiki/Classful_network
For a quick hack (that will certainly become broken with elaborate LAN configurations or IPv6), get a list of all IPs the current machine has, and strip out all IP:s that match any of the following:
10.* 127.* // <- Kudos to Brian for spotting the mistake 172.[16-31].* 192.168.*