Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Get Public IPv4 Address Using C#

Tags: address
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("

");

    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


This post first appeared on Programming, please read the originial post: here

Share the post

How to Get Public IPv4 Address Using C#

×

Subscribe to Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×