How do I determine the local host’s IPv4 addresses?
From my blog:
/// <summary>
/// This utility function displays all the IP (v4, not v6) addresses of the local computer.
/// </summary>
public static void DisplayIPAddresses()
{
StringBuilder sb = new StringBuilder();
// Get a list of all network interfaces (usually one per network card, dialup, and VPN connection)
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface network in networkInterfaces)
{
// Read the IP configuration for each network
IPInterfaceProperties properties = network.GetIPProperties();
// Each network interface may have multiple IP addresses
foreach (IPAddressInformation address in properties.UnicastAddresses)
{
// We're only interested in IPv4 addresses for now
if (address.Address.AddressFamily != AddressFamily.InterNetwork)
continue;
// Ignore loopback addresses (e.g., 127.0.0.1)
if (IPAddress.IsLoopback(address.Address))
continue;
sb.AppendLine(address.Address.ToString() + " (" + network.Name + ")");
}
}
MessageBox.Show(sb.ToString());
}
In particular, I do not recommend Dns.GetHostAddresses(Dns.GetHostName());
, regardless of how popular that line is on various articles and blogs.
add something like this to your code
if( IPAddress.Parse(a).AddressFamily == AddressFamily.InterNetwork )
// IPv4 address
Here's a function I use:
public static string GetIP4Address()
{
string IP4Address = String.Empty;
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily == AddressFamily.InterNetwork)
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
As an enumerable:
public static IEnumerable<string> GetIP4Addresses()
{
return Dns.GetHostAddresses(Dns.GetHostName())
.Where(IPA => IPA.AddressFamily == AddressFamily.InterNetwork)
.Select(x => x.ToString());
}