How to Get Public IP Address Using C#

In this post, we will see how to get public IP Address of a computer using C#.

In this post, we will see how to get the public IP Address of a computer using C#. Here’s the code snippet that does this:

  1. static string GetIPAddress()  
  2. {  
  3.     String address = "";  
  4.     WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");  
  5.     using (WebResponse response = request.GetResponse())  
  6.      using (StreamReader stream = new StreamReader(response.GetResponseStream()))  
  7.      {  
  8.         address = stream.ReadToEnd();  
  9.      }  
  10.   
  11.      int first = address.IndexOf("Address: ") + 9;  
  12.      int last = address.LastIndexOf("</body>");  
  13.      address = address.Substring(first, last - first);  
  14.   
  15.      return address;  

In the above code snippet, we are making a request to the website that displays the IP address of the current computer. We are receiving the response and parsing the response to get the IP address.

Hope you will like this. Keep learning and sharing.