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

655Z技术栈 C#编程 2小时前 3

在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地址,您可以根据自己的需求对上述代码进行调整和扩展。

提供PHP及ThinkPHP框架的定制开发、代码优化,PHP修改、ThinkPHP修改。

邮箱:yvsm@163.com 微信:yvsm316 QQ:316430983
关闭

用微信“扫一扫”