要同时获取IPv4和IPv6地址,可以通过以下C#代码实现:
using System; using System.Net; using System.Net.Sockets; class Program { static void Main() { string hostName = Dns.GetHostName(); IPAddress[] addresses = Dns.GetHostAddresses(hostName); foreach (IPAddress address in addresses) { if (address.AddressFamily == AddressFamily.InterNetwork) { Console.WriteLine("IPv4 Address: " + address.ToString()); } else if (address.AddressFamily == AddressFamily.InterNetworkV6) { Console.WriteLine("IPv6 Address: " + address.ToString()); } } } }
这段代码首先获取主机名,然后使用Dns.GetHostAddresses()
方法获取主机的所有IP地址。然后通过遍历IP地址数组,分别检查每个IP地址的AddressFamily属性,以区分IPv4和IPv6地址。最后打印出相应的IPv4和IPv6地址。