要獲取本地IP地址,可以使用以下代碼:
using System;
using System.Net;
using System.Net.Sockets;
class Program
{
static void Main()
{
string localIp = GetLocalIpAddress();
Console.WriteLine("Local IP Address: " + localIp);
}
static string GetLocalIpAddress()
{
string localIp = "";
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIp = ip.ToString();
break;
}
}
return localIp;
}
}
上面的代碼首先獲取當前主機的IP地址列表,然后遍歷列表找到IPv4地址并返回。最后在主函數中調用GetLocalIpAddress
方法獲取本地IP地址,并輸出到控制臺。