December 8th, 2008
Finding all local IP Addresses in C# - 1
A common problem is the find out the IP address of the machine your C# program is running on. C# provides two methods for obtaining the information. The first one is easy; but somewhat undocumented. The other one is just a little harder. If your code has to run on Mono then the second option is your only alternative.
C# originally provided basic system information through the System.Net.DNS class. By querying the DNS “GetHostEntry” we could also discover the local IP addresses. The problem is that under Mono this only returns the local loop-back connector making this not a portable solution.
In .NET 2.0 the System.Net.NetworkInformation class was added, which allows you to browse all the network adapters and query their configuration in much greater detail.
The code below shows both methods for querying the local configuration:
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Collections.Generic;
using System.Net.Sockets;
namespace IPLookup
{
class MainClass
{
public static IPAddress[] GetAllUnicastAddresses_Old()
{
// By passing an empty string to GetHostEntry we receive all the IP addresses on the local machine
// This breaks on Mono
IPHostEntry LocalEntry = Dns.GetHostEntry("");
return LocalEntry.AddressList;
}
public static IPAddress[] GetAllUnicastAddresses_New()
{
// This works on both Mono and .NET , but there is a difference: it also
// includes the LocalLoopBack so we need to filter that one out
List<IPAddress> Addresses = new List<IPAddress>();
// Obtain a reference to all network interfaces in the machine
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
IPInterfaceProperties properties = adapter.GetIPProperties();
foreach (IPAddressInformation uniCast in properties.UnicastAddresses)
{
// Ignore loop-back addresses & IPv6
if (!IPAddress.IsLoopback(uniCast.Address) && uniCast.Address.AddressFamily!= AddressFamily.InterNetworkV6)
Addresses.Add(uniCast.Address);
}
}
return Addresses.ToArray();
}
public static void Main(string[] args)
{
IPAddress[] Adresses = GetAllUnicastAddresses_Old();
foreach (IPAddress Adres in Adresses)
{
Console.WriteLine("OLD IP Address: {0}", Adres);
}
IPAddress[] Adresses2 = GetAllUnicastAddresses_New();
foreach (IPAddress Adres in Adresses2)
{
Console.WriteLine("NEW IP Address: {0}", Adres);
}
}
}
}









Except where otherwise noted, content on this site is
December 8th, 2008 at 6:20 pm
[...] Dijksterhuis.Org « Finding all local IP Addresses in C# [...]