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