How do I get the Local Network IP address of a computer programmatically?

If you are looking for the sort of information that the command line utility, ipconfig, can provide, you should probably be using the System.Net.NetworkInformation namespace.

This sample code will enumerate all of the network interfaces and dump the addresses known for each adapter.

using System;
using System.Net;
using System.Net.NetworkInformation;

class Program
{
    static void Main(string[] args)
    {
        foreach ( NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces() )
        {
            Console.WriteLine("Network Interface: {0}", netif.Name);
            IPInterfaceProperties properties = netif.GetIPProperties();
            foreach ( IPAddress dns in properties.DnsAddresses )
                Console.WriteLine("\tDNS: {0}", dns);
            foreach ( IPAddressInformation anycast in properties.AnycastAddresses )
                Console.WriteLine("\tAnyCast: {0}", anycast.Address);
            foreach ( IPAddressInformation multicast in properties.MulticastAddresses )
                Console.WriteLine("\tMultiCast: {0}", multicast.Address);
            foreach ( IPAddressInformation unicast in properties.UnicastAddresses )
                Console.WriteLine("\tUniCast: {0}", unicast.Address);
        }
    }
}

You are probably most interested in the UnicastAddresses.


Using Dns requires that your computer be registered with the local DNS server, which is not necessarily true if you're on a intranet, and even less likely if you're at home with an ISP. It also requires a network roundtrip -- all to find out info about your own computer.

The proper way:

NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach(NetworkInterface  adapter in  nics)
{
    foreach(var x in adapter.GetIPProperties().UnicastAddresses)
    {
        if (x.Address.AddressFamily == AddressFamily.InterNetwork  && x.IsDnsEligible)
        {
                    Console.WriteLine(" IPAddress ........ : {0:x}", x.Address.ToString());
        }
    }
}

(UPDATE 31-Jul-2015: Fixed some problems with the code)

Or for those who like just a line of Linq:

NetworkInterface.GetAllNetworkInterfaces()
    .SelectMany(adapter=> adapter.GetIPProperties().UnicastAddresses)
    .Where(adr=>adr.Address.AddressFamily == AddressFamily.InterNetwork  && adr.IsDnsEligible)
    .Select (adr => adr.Address.ToString());