4

我正在开发一个 Windows 应用程序,我需要找到本地机器的 IPv4 和 IPv6 地址。操作系统可以是 XP 或 Windows 7。

我有一个获取 MAC 地址的解决方案,例如,

string GetMACAddress()
{
    var macAddr =
        (
            from nic in NetworkInterface.GetAllNetworkInterfaces()
            where nic.OperationalStatus == OperationalStatus.Up
            select nic.GetPhysicalAddress().ToString()
        ).FirstOrDefault();

    return macAddr.ToString();
}

这适用于所有操作系统。

获取适用于 XP 和 WINDOWS 7 的 IPv4 和 IPv6 地址的正确方法是什么?

4

3 回答 3

7
string strHostName = System.Net.Dns.GetHostName();;
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
Console.WriteLine(addr[addr.Length-1].ToString());
if (addr[0].AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
            {
                Console.WriteLine(addr[0].ToString()); //ipv6
            }
于 2012-07-10T10:37:37.037 回答
2

要获取所有 IP4 和 IP6 地址,这是我的首选解决方案。请注意,它还会过滤环回 IP 地址,例如 127.0.0.1 或 ::1

public static IEnumerable<IPAddress> GetIpAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            return (from ip in host.AddressList where !IPAddress.IsLoopback(ip) select ip).ToList();
        }
于 2013-03-14T07:21:57.230 回答
0

这是我仅获取所有 IPv4 地址的方法。

    /// <summary>
    /// Gets/Sets the IPAddress(s) of the computer which the client is running on.
    /// If this isn't set then all IPAddresses which could be enumerated will be sent as
    /// a comma separated list.  
    /// </summary>
    public string IPAddress
    {
        set
        {
            _IPAddress = value;
        }
        get
        {
            string retVal = _IPAddress;

            // If IPAddress isn't explicitly set then we enumerate all IP's on this machine.
            if (_IPAddress == null)
            {
                // TODO: Only return ipaddresses that are for Ethernet Adapters

                String strHostName = Dns.GetHostName();
                IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
                IPAddress[] addr = ipEntry.AddressList;

                List<string> validAddresses = new List<string>();

                // Loops through the addresses and creates a list of valid ones.
                for (int i = 0; i < addr.Length; i++)
                {
                    string currAddr = addr[i].ToString();
                    if( IsValidIP( currAddr ) ) {
                        validAddresses.Add( currAddr );
                    }
                }

                for(int i=0; i<validAddresses.Count; i++)
                {
                    retVal += validAddresses[i];
                    if (i < validAddresses.Count - 1)
                    {
                        retVal += ",";
                    }
                }

                if (String.IsNullOrEmpty(retVal))
                {
                    retVal = String.Empty;
                }

            }

            return retVal;
        }
    }
于 2012-07-10T10:42:09.297 回答