How do I get only Internet Protocol version 4 addresses from Dns.GetHostAddresses()
? I have the code below, and it gives me IPv4 and IPv6 addresses.
I have to m
I use this helper method that returns the first active IPV4 address after filtering out the IPV6 and Loopback once
public static IPAddress GetLocalIPAddress()
{
IPAddress result = null;
IPHostEntry iphostentry = Dns.GetHostEntry(Dns.GetHostName());
IPAddress[] ipv4Address = Array.FindAll(iphostentry.AddressList, add => add.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(add));
if (ipv4Address.Length > 0 )
{
result =ipv4Address[0];
}
return result;
}
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());
}
For me the cleaner solution would be:
public static string GetLocalIP()
{
string ipv4Address = String.Empty;
foreach (IPAddress currentIPAddress in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (currentIPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
ipv4Address = currentIPAddress.ToString();
break;
}
}
return ipv4Address;
}
Here is a code to find the first connected IPv4 by using for loop :
IPAddress ipAddress = null;
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
for (int i=0 ; i<localIPs.Length ; i++)
{
if (localIPs[i].AddressFamily == AddressFamily.InterNetwork)
{
ipAddress = localIPs[i];
break;
}
}
Write locaIPs.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork)