C# 如何获取本地电脑IP地址
时间: 2023-10-19 19:36:19 浏览: 50
你可以使用C#中的System.Net.NetworkInformation.NetworkInterface类来获取本地电脑的IP地址。以下是获取本地IP地址的示例代码:
```csharp
using System.Net.NetworkInformation;
// 获取本地IP地址
string ipAddress = "";
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet || ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
{
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
ipAddress = ip.Address.ToString();
break;
}
}
}
if (!string.IsNullOrEmpty(ipAddress))
break;
}
Console.WriteLine("本地IP地址: " + ipAddress);
```
上述代码将遍历所有网络接口并查找Ethernet或Wireless80211接口的IP地址。如果找到了IPv4地址,则该地址将被赋值给`ipAddress`变量。请注意,如果您的计算机连接到多个网络,则可能会有多个IP地址,您需要根据您的需求进行相应的更改。