In the C#medium efficiency, obtain the internal and external IP address of the server
Get the grammar of the external IP address
<code class="language-csharp">string externalIP = new WebClient().DownloadString("https://ipv4.icanhazip.com/");</code>
Get the grammar of the internal IP address
<code class="language-csharp">string localIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault()?.ToString();</code>
Analysis of the previous code
<code class="language-csharp">string localIP = null; var host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { localIP = ip.ToString(); break; } }</code>
back to NULL to avoid potential abnormalities. It directly iterates the IP address list. After finding the first IPv4 address, it exits the cycle immediately, which improves efficiency. FirstOrDefault()
The above is the detailed content of How to Efficiently Get a Server's Internal and External IP Address in C#?. For more information, please follow other related articles on the PHP Chinese website!