Home > Backend Development > C++ > How to Efficiently Get a Server's Internal and External IP Address in C#?

How to Efficiently Get a Server's Internal and External IP Address in C#?

DDD
Release: 2025-01-26 06:06:08
Original
447 people have browsed it

How to Efficiently Get a Server's Internal and External IP Address in C#?

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:

<code class="language-csharp">string externalIP = new WebClient().DownloadString("https://ipv4.icanhazip.com/");</code>
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:

<code class="language-csharp">string localIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault()?.ToString();</code>
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:

<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>
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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template