c# 获取局域网ip

Fork Me On Github
zodream 编程技术 C# 2020年05月

获取本机局域网ip

AddressList必须倒序查找

c#
                            
/// <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 '';
    }
}
12345678910111213141516171819202122232425262728

获取局域网所有ip

这里用的是 ping 方法 ping 255 个地址

ts
                              

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());
    }
}
123456789101112131415161718192021222324252627282930

获取的时间为 2-3 秒,获取的也不一定准确

点击查看全文
0 395 0