Home >Backend Development >C++ >How Can I Get My Router's Public IP Address Using C# or Command-Line Tools?

How Can I Get My Router's Public IP Address Using C# or Command-Line Tools?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-18 11:17:09595browse

How Can I Get My Router's Public IP Address Using C# or Command-Line Tools?

Accessing Your Router's Public IP Address

This guide outlines several methods for determining your router's public IP address, using both C# code and command-line interfaces.

C# Methods

  • Utilizing HttpClient:
<code class="language-csharp">public static async Task<IPAddress> GetExternalIpAddress()
{
    string externalIpString = (await new HttpClient().GetStringAsync("http://icanhazip.com"))
        .Replace("\r\n", "").Replace("\n", "").Trim();
    if (!IPAddress.TryParse(externalIpString, out IPAddress ipAddress)) return null;
    return ipAddress;
}</code>
  • Using WebClient (Deprecated):
<code class="language-csharp">public static void Main(string[] args)
{
    string externalIpString = new WebClient().DownloadString("http://icanhazip.com").Replace("\r\n", "").Replace("\n", "").Trim();
    IPAddress externalIp = IPAddress.Parse(externalIpString);

    Console.WriteLine(externalIp.ToString());
}</code>

Command-Line Approaches

  • Linux and Windows Compatibility:
<code class="language-bash">wget -qO- http://bot.whatismyipaddress.com</code>
  • Using Curl:
<code class="language-bash">curl http://ipinfo.io/ip</code>

These examples demonstrate diverse techniques for obtaining your router's public IP, offering both programmatic (C#) and command-line solutions.

The above is the detailed content of How Can I Get My Router's Public IP Address Using C# or Command-Line Tools?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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