阅读量:0
要获取本地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地址,并输出到控制台。