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 with C# ?
192.168.1.1 is an IP address which routers like Linksys and other network brands use as an access point or gateway. Firms set up router admin access in this address to allow network administrators to configure their routers and networks.
An IP address, or Internet Protocol address, is a series of numbers that identifies any device on a network. Computers use IP addresses to communicate with each other both over the internet as well as on other networks.
Try this:
static IPAddress getInternetIPAddress()
{
try
{
IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName());
IPAddress gateway = IPAddress.Parse(getInternetGateway());
return findMatch(addresses, gateway);
}
catch (FormatException e) { return null; }
}
static string getInternetGateway()
{
using (Process tracert = new Process())
{
ProcessStartInfo startInfo = tracert.StartInfo;
startInfo.FileName = "tracert.exe";
startInfo.Arguments = "-h 1 208.77.188.166"; // www.example.com
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
tracert.Start();
using (StreamReader reader = tracert.StandardOutput)
{
string line = "";
for (int i = 0; i < 9; ++i)
line = reader.ReadLine();
line = line.Trim();
return line.Substring(line.LastIndexOf(' ') + 1);
}
}
}
static IPAddress findMatch(IPAddress[] addresses, IPAddress gateway)
{
byte[] gatewayBytes = gateway.GetAddressBytes();
foreach (IPAddress ip in addresses)
{
byte[] ipBytes = ip.GetAddressBytes();
if (ipBytes[0] == gatewayBytes[0]
&& ipBytes[1] == gatewayBytes[1]
&& ipBytes[2] == gatewayBytes[2])
{
return ip;
}
}
return null;
}
Note that this implementation of findMatch()
relies on class C matching. If you want to support class B matching, just omit the check for ipBytes[2] == gatewayBytes[2]
.
Edit History:
www.example.com
.getInternetIPAddress()
, to show how to use the other methods.FormatException
if getInternetGateway()
failed to parse the gateway IP. (This can happen if the gateway router is configured such that it doesn't respond to traceroute requests.)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With