Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Try this:</p> <pre><code>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 &lt; 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] &amp;&amp; ipBytes[1] == gatewayBytes[1] &amp;&amp; ipBytes[2] == gatewayBytes[2]) { return ip; } } return null; } </code></pre> <p>Note that this implementation of <code>findMatch()</code> relies on class C matching. If you want to support class B matching, just omit the check for <code>ipBytes[2] == gatewayBytes[2]</code>.</p> <p><strong>Edit History:</strong></p> <ul> <li>Updated to use <code>www.example.com</code>.</li> <li>Updated to include <code>getInternetIPAddress()</code>, to show how to use the other methods.</li> <li>Updated to catch <code>FormatException</code> if <code>getInternetGateway()</code> failed to parse the gateway IP. (This can happen if the gateway router is configured such that it doesn't respond to <a href="http://en.wikipedia.org/wiki/Traceroute" rel="noreferrer">traceroute</a> requests.)</li> <li>Cited Brian Rasmussen's comment.</li> <li>Updated to use the IP for www.example.com, so that it works even when the DNS server is down.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload