Home > Backend Development > C++ > How Can I Get My Server's IP Address Using C#?

How Can I Get My Server's IP Address Using C#?

Linda Hamilton
Release: 2025-01-26 05:56:12
Original
726 people have browsed it

How Can I Get My Server's IP Address Using C#?

Retrieving Your Server's IP Address in C#

Knowing your server's IP address is crucial for many server-side applications. C# offers convenient ways to obtain this information using the Dns class and external web services.

Here's a code example to get the local IP address:

<code class="language-csharp">IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
    if (ip.AddressFamily == AddressFamily.InterNetwork)
    {
        localIP = ip.ToString();
        break; 
    }
}
return localIP;</code>
Copy after login

This code snippet retrieves the hostname using Dns.GetHostName() and then iterates through the associated IP addresses. It specifically selects the IPv4 address (AddressFamily.InterNetwork) and returns it.

Alternatively, to obtain the server's external IP address (useful when behind a NAT):

<code class="language-csharp">string externalIP = "";
using (var client = new WebClient())
{
    externalIP = client.DownloadString("http://icanhazip.com").TrimEnd();
}
return externalIP;</code>
Copy after login

This approach uses the icanhazip.com web service, which returns the public IP address as plain text.

Both methods provide reliable ways to access your server's IP address within a C# application. The second method is especially helpful for scenarios where the internal and external IPs differ, such as servers behind Network Address Translation (NAT).

The above is the detailed content of How Can I Get My Server's IP Address Using 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template