Get all IP Addresses of the system in C#

First of all, the question arises,
Can a computer have more than one IP?

If a computer is connected to one network, then it can have only one unique IP Address.

But if a computer is connected to more than one network,

 

For example, a computer is connected to two Ethernet networks (via different adapters) and to a Wi-Fi network,

then it will have 3 different IP Addresses assigned: one for each network.

 

Following C# code will populate the List with all the IP addresses on the system:

List<string> ipsList = new List<string>();

foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
   IPInterfaceProperties ipProps = netInterface.GetIPProperties();

   foreach (UnicastIPAddressInformation addr in ipProps.UnicastAddresses)
   {
       ipsList.Add(addr.Address.ToString());
   }
}

 

The above code will evaluate to all IPv4 and IPv6 addresses.

 

IPv4 format:   192.168.10.20

IPv6 format:   FE80:0000:0000:0000:0202:B3FF:FE1E:8329

IPv4 and IPv6 addresses can be identified by looking into the IPAddress.AddressFamily property.

if the AddressFamily is InterNetwork, then it is an IPv4 address.
if the AddressFamily is InterNetworkV6, then it is an IPv6 address.

In the above code, check the AddressFamily property as follows:

if(addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) 
{ 
       //then it is IPV4
}

if(addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
       //then it is IPV6.
}