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

66,542

Solution 1

In How to get IP addresses in .NET with a host name by John Spano, it says to add the System.Net namespace, and use the following code:

//To get the local IP address 
string sHostName = Dns.GetHostName (); 
IPHostEntry ipE = Dns.GetHostByName (sHostName); 
IPAddress [] IpA = ipE.AddressList; 
for (int i = 0; i < IpA.Length; i++) 
{ 
    Console.WriteLine ("IP Address {0}: {1} ", i, IpA[i].ToString ()); 
}

Solution 2

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.

Solution 3

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());

Solution 4

As a machine can have multiple ip addresses, the correct way to figure out your ip address that you're going to be using to route to the general internet is to open a socket to a host on the internet, then inspect the socket connection to see what the local address that is being used in that connection is.

By inspecting the socket connection, you will be able to take into account weird routing tables, multiple ip addresses and whacky hostnames. The trick with the hostname above can work, but I wouldn't consider it entirely reliable.

Solution 5

If you know there are one or more IPv4 addresses for your computer, this will provide one of them:

Dns.GetHostAddresses(Dns.GetHostName())
    .First(a => a.AddressFamily == AddressFamily.InterNetwork).ToString()

GetHostAddresses normally blocks the calling thread while it queries the DNS server, and throws a SocketException if the query fails. I don't know whether it skips the network call when looking up your own host name.

Share:
66,542

Related videos on Youtube

Redwood
Author by

Redwood

I'm a San Francisco Bay Area programmer working in Objective-C/Cocoa and C#/.NET.

Updated on July 09, 2022

Comments

  • Redwood
    Redwood almost 2 years

    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?

  • Scott Marlowe
    Scott Marlowe over 15 years
    GetHostByName showing as deprecated. wound up using: IPAddress[] ipAddress = Dns.GetHostAddresses (strHostName); accomplishes same thing.
  • FosterZ
    FosterZ over 12 years
    hey James, ha NetworkInformation from your answer line no:2, c# compiler saying "type or namespace could not be found", i have imported System.Net.NetworkInformation already then also its saying "type or namespace missing", whats the deal ?
  • user664939
    user664939 over 12 years
    @FosterZ: I agree (it doesn't work as is). I implemented this code as: foreach ( NetworkInterface ni in nics ) { foreach ( UnicastIPAddressInformation x in ni.GetIPProperties().UnicastAddresses ) { if ( x.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ) { Console.WriteLine( " IPAddress ........ : {0:x}", x.Address.ToString() ); } } } and it printed out a mixture of most of my actual IP addresses and some other not-my-ip-addresses.
  • Siarhei Kuchuk
    Siarhei Kuchuk over 12 years
    static IPAddress[] GetAddresses(string host) { return Dns.GetHostAddresses(host); }