05/06/2015 by Nitesh

How To Get Public IP Address Using C#


In this post, we will see how can we get public IP Address of a computer using C#. We will make use of WebRequest class to make a call to the server that returns the IP address of the machine that made the request. Here’s the code snippet that does this –

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

      //Search for the ip in the html
      int first = address.IndexOf("Address: ") + 9;
      int last = address.LastIndexOf("");
      address = address.Substring(first, last - first);

      return address;

In the above code snippet, we are making a request to the website http://checkip.dyndns.org 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 like this. Keep learning and sharing.

#.Net#C##IP Address