问题
I am developing a windows application and I need to find the IPv4 and IPv6 address of local machine. OS can be XP or Windows 7.
I got a solution for getting MAC address like,
string GetMACAddress()
{
var macAddr =
(
from nic in NetworkInterface.GetAllNetworkInterfaces()
where nic.OperationalStatus == OperationalStatus.Up
select nic.GetPhysicalAddress().ToString()
).FirstOrDefault();
return macAddr.ToString();
}
This is working in all OS.
What is the correct way to get IPv4 and IPv6 address that work on XP and WINDOWS 7?
回答1:
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
}
回答2:
To get all IP4 and IP6 address, here is my preferred solution. Note that it also filters the loopback IP addresses like 127.0.0.1 or ::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();
}
回答3:
Here's my method for getting all the IPv4 addresses only.
/// <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;
}
}
来源:https://stackoverflow.com/questions/11411486/how-to-get-ipv4-and-ipv6-address-of-local-machine