c#

C#获取IP地址的最佳实践分享

小樊
91
2024-07-06 01:43:27
栏目: 编程语言

在C#中获取IP地址的最佳实践是使用System.Net.NetworkInformation命名空间中的NetworkInterface类。以下是一个简单的示例代码,演示如何获取本地计算机上所有网络接口的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()方法获取本地计算机上的所有网络接口。然后遍历每个网络接口,检查其状态是否为OperationalStatus.Up,以确保它是活动的。然后通过GetIPProperties()方法获取该网络接口的IP属性,并遍历其UnicastAddresses属性以获取所有的IP地址。

这种方法可以帮助您获取本地计算机上所有网络接口的IP地址,您可以根据自己的需求对上述代码进行调整和扩展。

0
看了该问题的人还看了