溫馨提示×

C#獲取IP地址的最佳實踐分享

c#
小樊
91
2024-07-06 01:43:27
欄目: 編程語言

在C#中獲取IP地址的最佳實踐是使用System.Net.NetworkInformation命名空間中的NetworkInterface類。以下是一個簡單的示例代碼,演示如何獲取本地計算機上所有網(wǎng)絡接口的IP地址:

using System;
using System.Net;
using System.Net.NetworkInformation;

class Program
{
    static void Main()
    {
        NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

        foreach (NetworkInterface networkInterface in networkInterfaces)
        {
            if (networkInterface.OperationalStatus == OperationalStatus.Up)
            {
                IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
                UnicastIPAddressInformationCollection ipAddresses = ipProperties.UnicastAddresses;

                Console.WriteLine($"Interface: {networkInterface.Name}");
                foreach (UnicastIPAddressInformation ipAddress in ipAddresses)
                {
                    Console.WriteLine($"IP Address: {ipAddress.Address}");
                }
            }
        }
    }
}

在上面的示例中,我們首先使用NetworkInterface.GetAllNetworkInterfaces()方法獲取本地計算機上的所有網(wǎng)絡接口。然后遍歷每個網(wǎng)絡接口,檢查其狀態(tài)是否為OperationalStatus.Up,以確保它是活動的。然后通過GetIPProperties()方法獲取該網(wǎng)絡接口的IP屬性,并遍歷其UnicastAddresses屬性以獲取所有的IP地址。

這種方法可以幫助您獲取本地計算機上所有網(wǎng)絡接口的IP地址,您可以根據(jù)自己的需求對上述代碼進行調(diào)整和擴展。

0