Get External IP Address over Remoting in C#

How to Get Public IPv4 Address Using C#

In this article, we will see the multiple examples to get the public IP Address of a computer using C#.
You should check out the docs.

Example 1,

static string GetPublicIPAddress()
{
    String address = "";
    WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
    using (WebResponse response = request.GetResponse())
    using (System.IO.StreamReader stream = new System.IO.StreamReader(response.GetResponseStream()))
    {
        address = stream.ReadToEnd();
    }

    int first = address.IndexOf("Address: ") + 9;
    int last = address.LastIndexOf("</body>");
    address = address.Substring(firstlast - first);

    return address;
}


Example 2,

private string GetPublicIPAddress()
{
  var request = (HttpWebRequest)WebRequest.Create("http://ifconfig.me");
  request.UserAgent = "curl"// this will tell the server to return the information as if the request was made by the linux "curl" command
  string publicIPAddress;
  request.Method = "GET";
  using(WebResponse response = request.GetResponse())
  {
      using(var reader = new System.IO.StreamReader(response.GetResponseStream()))
      {
        publicIPAddress = reader.ReadToEnd();
      }
  }
  return publicIPAddress.Replace("\n""");
}

Example 3,

public static string GetPublicIPAddress ()
{
    string url = "http://checkip.dyndns.org";
    System.Net.WebRequest req = System.Net.WebRequest.Create(url);
    System.Net.WebResponse resp = req.GetResponse();
    System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
    string response = sr.ReadToEnd().Trim();
    string[] a = response.Split(':');
    string a2 = a[1].Substring(1);
    string[] a3 = a2.Split('<');
    string ip = a3[0];
    
    return ip;
}


You must see this - How to get public IP address in JavaScript | jQuery
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^