获取本机局域网ip
AddressList
必须倒序查找
/// <summary>
/// 获取本机IP地址
/// </summary>
/// <returns>本机IP地址</returns>
public static string GetLocalIP()
{
try
{
var hostName = Dns.GetHostName(); //得到主机名
var ipEntry = Dns.GetHostEntry(HostName);
var ips = ipEntry.AddressList;
for (int i = ips.Length - 1; i >= 0; i--)
{
//从IP地址列表中筛选出IPv4类型的IP地址
//AddressFamily.InterNetwork表示此IP为IPv4,
//AddressFamily.InterNetworkV6表示此地址为IPv6类型
if (ips[i].AddressFamily == AddressFamily.InterNetwork)
{
return ips[i].ToString();
}
}
return "";
}
catch (Exception ex)
{
return '';
}
}
获取局域网所有ip
这里用的是 ping
方法 ping
255 个地址
private List<string> ipItems = new List<string>();
/// <summary>
/// 获取局域网的其他ip
/// </summary>
/// <param name="baseIp"></param>
/// <param name="exsits"></param>
private void LoadAllIp(string baseIp, string exsits)
{
for (int i = 1; i <= 255; i++)
{
var ip = baseIp + i;
if (ip == exsits)
{
continue;
}
var ping = new Ping();
ping.PingCompleted += Ping_PingCompleted;
ping.SendAsync(ip, 2000, null);
}
}
private void Ping_PingCompleted(object sender, PingCompletedEventArgs e)
{
if (e.Reply.Status == IPStatus.Success)
{
ipItems.Add(e.Reply.Address.ToString());
}
}
获取的时间为 2-3 秒,获取的也不一定准确
转载请保留原文链接: https://zodream.cn/blog/id/150.html