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 make it work with boxes that have multiple IPv4 addresses.
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
private void get_IPs()
{
foreach (IPAddress a in localIPs)
{
server_ip = server_ip + a.ToString() + "/";
}
}
add something like this to your code
if( IPAddress.Parse(a).AddressFamily == AddressFamily.InterNetwork )
// IPv4 address
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.
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());
}
Very Clean and sweet when using Linq
IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName()).Where(a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToArray();
Write locaIPs.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork)
From MSDN on Dns.GetHostAddresses,
When an empty string is passed as the host name, this method returns the IPv4 addresses of the local host for all operating systems except Windows Server 2003; for Windows Server 2003, both IPv4 and IPv6 addresses for the local host are returned.
IPv6 addresses are filtered from the results of the GetHostAddresses method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty IPAddress instance if only IPv6 results where available for the hostNameOrAddress.parameter.
So, you can use this to try and parse it:
IPAddress.TryParse
then check AddressFamily
which
Returns System.Net.Sockets.AddressFamily.InterNetwork for IPv4 or System.Net.Sockets.AddressFamily.InterNetworkV6 for IPv6.
string input = "192.168.0.10";
IPAddress address;
if (IPAddress.TryParse(input, out address))
{
switch (address.AddressFamily)
{
case System.Net.Sockets.AddressFamily.InterNetwork:
// we have IPv4
break;
case System.Net.Sockets.AddressFamily.InterNetworkV6:
// we have IPv6
break;
default:
// do something else
break;
}
}
I used the answer that started with
/// <summary> and it mostly worked:
//for some reason Visual Studio 2010 did not understand AddressFamily.Inernetwork
if (address.Address.AddressFamily != AddressFamily.InterNetwork)
I had to use:
if(address.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
but I actually used:
if(!address.Address.AddressFamily.Equals(System.Net.Sockets.AddressFamily.InterNetwork))
Also, I added:
if (network.OperationalStatus != OperationalStatus.Up)
continue;
Because there were some networks which didn't work and should never have been there, I did see that they were in the registry. ---Alvin
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;
}
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;
}
This is my code. And can find it on many LAN cards.
private string GetLocalIpAddress()
{
string localIpAddress = string.Empty;
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface nic in nics)
{
if (nic.OperationalStatus != OperationalStatus.Up)
{
continue;
}
IPv4InterfaceStatistics adapterStat = (nic).GetIPv4Statistics();
UnicastIPAddressInformationCollection uniCast = (nic).GetIPProperties().UnicastAddresses;
if (uniCast != null)
{
foreach (UnicastIPAddressInformation uni in uniCast)
{
if (adapterStat.UnicastPacketsReceived > 0
&& adapterStat.UnicastPacketsSent > 0
&& nic.NetworkInterfaceType != NetworkInterfaceType.Loopback)
{
if (uni.Address.AddressFamily == AddressFamily.InterNetwork)
{
localIpAddress = nic.GetIPProperties().UnicastAddresses[0].Address.ToString();
break;
}
}
}
}
}
return localIpAddress;
}
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;
}
}
来源:https://stackoverflow.com/questions/6668810/how-do-i-determine-the-local-host-s-ipv4-addresses