C# Programming – Get the public IP address of the computer

1. Handling:

To solve the problem of getting the computer’s public IP address, I will do the following:

+ Go to http://checkip.dyndns.org/ and read the HTML content sent.

When accessing http://checkip.dyndns.org/ in a browser.

+ Process the string and extract the content and return the desired result (public IP address).

2. Build a simple program

I will build a simple program in the form of Console Application (.NET Framework), then perform the procedure to get the computer’s public IP address and display it on the Console window screen.

The C# code is as follows:

using System;
using System.IO;
using System.Net;

namespace GetPublicIP
    class Program
        static void Main(string[] args)
            string publicIp = GetPublicIPAddress();

            Console.WriteLine($"Current IP Address: {publicIp}");


        static string GetPublicIPAddress()
            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();

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

            return address;

3. Result:

Result when running the program.

For safety and privacy reasons, I masked the IP address on the pictures.

4. Related articles

This article deals with the C# programming language. Therefore, if you are interested, you can read more articles related to the C# programming language below.

5. Conclusion

This is a relatively short article, I have come up with a way to get the public IP address (public IP) when using the C# programming language. If you have any other solution, please share it with me!

Finally, thank you for reading the article, if you find it interesting, please share the article to more people! I will be very happy for that!

Be the first to comment

Leave a Reply

Your email address will not be published.