你可以通過下面的方法來獲取本機的IP地址:
using System.Net;
using System.Net.Sockets;
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
return "";
}
調用這個方法即可獲取本機的IP地址:
string ipAddress = GetLocalIPAddress();
Console.WriteLine(ipAddress);