溫馨提示×

C#如何同時獲取IPv4和IPv6地址

c#
小樊
166
2024-07-06 01:44:19
欄目: 編程語言

要同時獲取IPv4和IPv6地址,可以通過以下C#代碼實現(xiàn):

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());
            }
        }
    }
}

這段代碼首先獲取主機(jī)名,然后使用Dns.GetHostAddresses()方法獲取主機(jī)的所有IP地址。然后通過遍歷IP地址數(shù)組,分別檢查每個IP地址的AddressFamily屬性,以區(qū)分IPv4和IPv6地址。最后打印出相應(yīng)的IPv4和IPv6地址。

0