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

Lawrence Johnston picture Lawrence Johnston · Sep 30, 2008 · Viewed 65.2k times · Source

I need to get the actual local network IP address of the computer (e.g. 192.168.0.220) from my program using C# and .NET 3.5. I can't just use 127.0.0.1 in this case.

How can I accomplish this?

Answer

GBegen picture GBegen · Sep 30, 2008

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.