Home >Backend Development >C++ >How to Efficiently Get a Server's Internal and External IP Address in C#?
Get the grammar of the external IP address
<code class="language-csharp">string externalIP = new WebClient().DownloadString("https://ipv4.icanhazip.com/");</code>This code uses the "iCanhazip" service to obtain the public IP address of the server.
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>The IP address list associated with the server host name iteration and select the address corresponding to the IPv4 address family.
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>This version uses a clearer circulatory structure and processes the situation of
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!