In the C#medium efficiency, obtain the internal and external IP address of the server
During network management or application debugging, the IP address of the server is often required. This article aims to clarify grammar and provide a method of optimization to retrieve this information.
Get the grammar of the external IP address
To determine the external IP address of the computer (visible to the Internet), please use the following code:
string externalIP = new WebClient().DownloadString("https://ipv4.icanhazip.com/");
Copy after login
This code uses the "iCanhazip" service to obtain the public IP address of the server.
Get the grammar of the internal IP address
To retrieve the internal IP address of the server (in the local network), please use the following technologies:
string localIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault()?.ToString();
Copy after login
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
The code provided in the problem is an effective method, but it can enhance its readability and efficiency. The modified version below includes these improvements:
string localIP = null;
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
break;
}
}
Copy after login
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!