温馨提示×

C#如何同时获取IPv4和IPv6地址

c#
小樊
173
2024-07-06 01:44:19
栏目: 编程语言

要同时获取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地址。

0