Search code examples
c#ip-address

How to get the public IP v4 address


I'm using following code to get the ip v4 address:

IPAddress[] ipAddress = Dns.GetHostAddresses(mycomputerName);
foreach (IPAddress ipaddr in ipAddress)
{
    if (ipaddr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
    {
        Console.WriteLine(ipaddr);
    }
}

During test, I found that I will get three ip address:
192.168.241.1
192.168.200.1
10.108.150.48

The frist and Second address are my vmware network address. How to get the public ip address only?


Solution

  • You have to call this site from web client and get your public ip.

     string public = new WebClient().DownloadString("http://icanhazip.com");