xamarin.Android:获取局域网络

通过Java.Net 层,调用Java接口

/// <summary>
        /// 获取网络列表
        /// </summary>
        private Dictionary<string, NetworkInfoBean> GetNetworkInfoList()
        {
            Dictionary<string, NetworkInfoBean> result = new Dictionary<string, NetworkInfoBean>();
            var nis = Java.Net.NetworkInterface.NetworkInterfaces;
            if (nis == null) return result;
            while (nis.HasMoreElements)
            {
                var ni = nis.NextElement() as Java.Net.NetworkInterface;
                var macBuilder = new StringBuilder();
                byte[] bytes = ni?.GetHardwareAddress();
                if (bytes != null)
                {
                    int len = bytes.Length;
                    for (int i = 0; i < len; i++)
                    {
                        if (i != 0)
                        {
                            macBuilder.Append(":");
                        }
                        macBuilder.Append(HEX_DIGITS[bytes[i] >> 4 & 0x0f]).Append(HEX_DIGITS[bytes[i] & 0x0f]);
                    }
                }

                if(ni.InterfaceAddresses?.Count == 0) continue;
                string mac = macBuilder.ToString();
                foreach (var addr in ni.InterfaceAddresses)
                {
                    var hostAddress = addr.Address.HostAddress;
                    //Ipv4
                    if (hostAddress.IndexOf(":") < 0)
                    {
                        var mask = GetSubnetMaskFromPrefixLength(addr.NetworkPrefixLength);
                        result.Add(ni.Name, new NetworkInfoBean(ni.Name, mac, hostAddress, mask.ToString()));
                    }
                }
            }

            return result;
        }

        private bool AppendSpec(string name, Dictionary<string, NetworkInfoBean> networkInfoList, StringBuilder builder, Func<NetworkInfoBean, string> function)
        {
            networkInfoList.TryGetValue(name, out NetworkInfoBean infoBean);
            if (infoBean == null) return false;
            
            var value = function.Invoke(infoBean);

            if (builder.IndexOf(value) != -1) return true;
            if (builder.Length() != 0) builder.Append("\n");
            
            builder.Append(value);
            return true;
        }

        public  void  GetNetworkState()
        {
            Dictionary<string, NetworkInfoBean> networkInfoList = GetNetworkInfoList();

            Console.WriteLine("--------GetNetworkState-----------");
            foreach (var networkInfo in networkInfoList)
            {
                Console.WriteLine($"name: {networkInfo.Value.Name}  Ip: {networkInfo.Value.Ip}  mac:{networkInfo.Value.Mac} mask:{networkInfo.Value.Mask}");
            }

            StringBuilder ipBuilder = new StringBuilder();
            StringBuilder wifiMacBuilder = new StringBuilder();
            StringBuilder ethMacBuilder = new StringBuilder();
            AppendSpec("wlan0", networkInfoList, ipBuilder, networkInfoBean => networkInfoBean.Ip);  // Wifi
            AppendSpec("p2p0", networkInfoList, ipBuilder, networkInfoBean => networkInfoBean.Ip);   //热点
            AppendSpec("eth", networkInfoList, ipBuilder, networkInfoBean => networkInfoBean.Ip); //有线

            AppendSpec("wlan0", networkInfoList, wifiMacBuilder, networkInfoBean =>  networkInfoBean.Mac);
            AppendSpec("p2p0", networkInfoList, wifiMacBuilder, networkInfoBean =>  networkInfoBean.Mac);
            AppendSpec("eth", networkInfoList, ethMacBuilder, networkInfoBean => networkInfoBean.Mac);
        }

        private char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
 /// <summary>
        /// 获取子网掩码
        /// </summary>
        /// <param name="prefixLength"></param>
        /// <returns></returns>
        private IPAddress GetSubnetMaskFromPrefixLength(int prefixLength)
        {
            var maskBytes = new byte[4];
            var remainingBits = prefixLength;
            for (var i = 0; i < 4; i++)
            {
                var bitsToSet = Math.Min(remainingBits, 8);
                maskBytes[i] = (byte) (((1 << bitsToSet) - 1) << (8 - bitsToSet));
                remainingBits -= bitsToSet;
            }

            return new IPAddress(maskBytes);
        }

自定义类

 public class NetworkInfoBean
    {
        /// <summary>
        ///类型名称
        /// </summary>
        public string Name { get; set; }
        public string Mac { get; set; }
        public string Ip { get; set; }
        /// <summary>
        /// 子网掩码
        /// </summary>
        public string Mask { get; set; }

        public NetworkInfoBean(string name, string mac, string ip,string mask)
        {
            Name = name;
            Mac = mac;
            Ip = ip;
            Mask = mask;
        }

        public override string ToString()
        {
            return $"NetworkInfoBean{{name='{Name}', mac='{Mac}', ip='{Ip}', mask='{Mask}'}}";
        }
    }

 

posted on 2023-08-18 11:53  TanZhiWei  阅读(36)  评论(0编辑  收藏  举报