c# - 如何以编程方式获取计算机的本地网络 IP 地址?

标签 c# .net .net-3.5 ip-address

我需要使用 C# 和 .NET 3.5 从我的程序中获取计算机的实际本地网络 IP 地址(例如 192.168.0.220)。在这种情况下,我不能只使用 127.0.0.1。

我怎样才能做到这一点?

最佳答案

如果您正在寻找命令行实用程序 ipconfig 可以提供的信息,您可能应该使用 System.Net.NetworkInformation 命名空间。

此示例代码将枚举所有网络接口(interface)并转储每个适配器的已知地址。

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

class Program
{
    static void Main(string[] args)
    {
        foreach ( NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces() )
        {
            Console.WriteLine("Network Interface: {0}", netif.Name);
            IPInterfaceProperties properties = netif.GetIPProperties();
            foreach ( IPAddress dns in properties.DnsAddresses )
                Console.WriteLine("\tDNS: {0}", dns);
            foreach ( IPAddressInformation anycast in properties.AnycastAddresses )
                Console.WriteLine("\tAnyCast: {0}", anycast.Address);
            foreach ( IPAddressInformation multicast in properties.MulticastAddresses )
                Console.WriteLine("\tMultiCast: {0}", multicast.Address);
            foreach ( IPAddressInformation unicast in properties.UnicastAddresses )
                Console.WriteLine("\tUniCast: {0}", unicast.Address);
        }
    }
}

您可能对 UnicastAddresses 最感兴趣。

关于c# - 如何以编程方式获取计算机的本地网络 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/151231/

相关文章:

c# - WPF 在代码后面初始化对象并在 View 模型中使用该对象

c# - ASP.NET MVC 中的基本 "add user/edit user"表单例份验证功能

c# - 如何在 C# 中使用泛型声明变量

c# - ZipArchive 在实时服务器上提供无效文件

c# - 具有足够精度以实现计算器的数字类型

c# - 对象可以跨不同的框架版本序列化/反序列化吗?

.net - 下载 .NET 3.5 的 Entity Framework

c# - 在页面 PreInit 事件中访问 Asp.NET 控件

.net - WinForms 到 WPF - 我们如何从这里到达那里?

unit-testing - 如何为 Moq 和 Linq-to-Sql 编写 CRUD 单元测试