要同時獲取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地址。