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

5

28

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?

Kimberli answered 29/9, 2008 at 23:51 Comment(0)
S
24

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 ()); 
}
Southdown answered 29/9, 2008 at 23:53 Comment(3)
Which IP Address in the array that you get back is the right one?Angst
GetHostByName showing as deprecated. wound up using: IPAddress[] ipAddress = Dns.GetHostAddresses (strHostName); accomplishes same thing.Brennabrennan
static IPAddress[] GetAddresses(string host) { return Dns.GetHostAddresses(host); }Indicative
V
39

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.

Vtol answered 30/9, 2008 at 0:33 Comment(0)
A
27

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());
Auriculate answered 30/9, 2008 at 0:49 Comment(2)
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 ?Carisa
@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.Gopherwood
S
24

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 ()); 
}
Southdown answered 29/9, 2008 at 23:53 Comment(3)
Which IP Address in the array that you get back is the right one?Angst
GetHostByName showing as deprecated. wound up using: IPAddress[] ipAddress = Dns.GetHostAddresses (strHostName); accomplishes same thing.Brennabrennan
static IPAddress[] GetAddresses(string host) { return Dns.GetHostAddresses(host); }Indicative
U
11

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.

Unofficial answered 30/9, 2008 at 0:2 Comment(0)
L
1

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.

Latinist answered 17/10, 2013 at 16:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.