如何确定本地主机的IPv4地址?

时间:2011-07-12 17:58:07

标签: c# ip-address ipv4

如何仅从Dns.GetHostAddresses()获取Internet Protocol version 4个地址?我有下面的代码,它给我IPv4和IPv6地址。 我必须使用具有多个IPv4地址的盒子。

IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
private void get_IPs()
    {
        foreach (IPAddress a in localIPs)
        {
           server_ip = server_ip + a.ToString() + "/";
        }
    }

11 个答案:

答案 0 :(得分:36)

来自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()); 
}

特别是,我推荐Dns.GetHostAddresses(Dns.GetHostName());,无论这条线在各种文章和博客上的受欢迎程度如何。

答案 1 :(得分:27)

在代码中添加类似的内容

  if( IPAddress.Parse(a).AddressFamily == AddressFamily.InterNetwork )
  // IPv4 address

答案 2 :(得分:11)

这是我使用的功能:

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;
}

作为一个可枚举的:

public static IEnumerable<string> GetIP4Addresses()
{
    return Dns.GetHostAddresses(Dns.GetHostName())
        .Where(IPA => IPA.AddressFamily == AddressFamily.InterNetwork)
        .Select(x => x.ToString());
}

答案 3 :(得分:7)

使用Linq时非常干净和甜美

IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName()).Where(a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToArray();

答案 4 :(得分:4)

撰写locaIPs.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork)

答案 5 :(得分:4)

来自MSDN on Dns.GetHostAddresses

  

当空字符串作为主机名传递时,此方法返回   所有操作系统的本地主机的IPv4地址除外   Windows Server 2003;对于Windows Server 2003,IPv4和IPv6   返回本地主机的地址。

     

从GetHostAddresses的结果中过滤掉IPv6地址   如果本地计算机没有安装IPv6,则为方法。作为一个   结果,如果只是,可以返回一个空的IPAddress实例   IPv6结果可用于hostNameOrAddress.parameter。

因此,您可以将其用于try and parse it

IPAddress.TryParse

然后检查AddressFamily哪个

  

返回适用于IPv4或的System.Net.Sockets.AddressFamily.InterNetwork   用于IPv6的System.Net.Sockets.AddressFamily.InterNetworkV6。

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;
    }
}

答案 6 :(得分:1)

我使用了以

开头的答案
/// <summary> and it mostly worked:
//for some reason Visual Studio 2010 did not understand AddressFamily.Inernetwork
    if (address.Address.AddressFamily != AddressFamily.InterNetwork) 

我不得不使用:

if(address.Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)

但实际上我用过:

if(!address.Address.AddressFamily.Equals(System.Net.Sockets.AddressFamily.InterNetwork))

另外,我补充道:

if (network.OperationalStatus != OperationalStatus.Up)
                continue;

因为有些网络不起作用而且本来不应该在那里,我确实看到它们在注册表中。 ---阿尔文

答案 7 :(得分:0)

对我来说,更清洁的解决方案是:

 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;
        }

答案 8 :(得分:0)

我使用这个帮助方法,在过滤掉IPV6和Loopback一次后返回第一个活动的IPV4地址


    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;
    }

答案 9 :(得分:0)

这是我的代码。 并且可以在许多LAN卡上找到它。

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;
}

答案 10 :(得分:0)

以下是使用for循环查找第一个连接的IPv4的代码:

        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;
            }                
        }