如何获得本地机器的IPv4和IPv6地址? [英] How to get IPv4 and IPv6 address of local machine?
本文介绍了如何获得本地机器的IPv4和IPv6地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一个Windows应用程序,我需要找到本地计算机的IPv4和IPv6地址。操作系统可以是XP或Windows 7。
我得到了一个解决方案,用于获取MAC地址一样,
字符串GetMACAddress()
{
VAR MACADDR =
(
从网卡中NetworkInterface.GetAllNetworkInterfaces()
其中,nic.OperationalStatus == OperationalStatus.Up
选择nic.GetPhysicalAddress()的ToString()
).FirstOrDefault();
返回macAddr.ToString();
}
这是工作在所有的操作系统。
什么是正确的方式来获得IPv4和IPv6地址在XP和Windows 7的这项工作?
解决方案
字符串strHostName = System.Net.Dns.GetHostName();;
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
ip地址[]地址= ipEntry.AddressList;
Console.WriteLine(地址[addr.Length-1]的ToString());
如果(地址[0] == .AddressFamily System.Net.Sockets.AddressFamily.InterNetworkV6)
{
Console.WriteLine(地址[0]的ToString()); // IPv6的
}
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?
解决方案
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
}
这篇关于如何获得本地机器的IPv4和IPv6地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文