我需要使用 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/