using System.Linq; using System.Net; using System.Net.Sockets; /// <summary> /// 获取本机内网 IPv4 地址 /// </summary> /// <returns></returns> public static string GetLocalIPv4() { var ipv4s = Dns.GetHostAddresses(Dns.GetHostName()) //根据主机名称解析主机ip地址 .Where(p => p.AddressFamily == AddressFamily.InterNetwork) //筛选出所有ipv4地址 .Select(p => p.MapToIPv4().ToString()); if (ipv4s.Count() > 1) return ipv4s.Where(p => p.StartsWith("192")).FirstOrDefault(); //如果有多个,返回192开头的ipv4地址 else return ipv4s.FirstOrDefault(); }