public static IPAddress GetBroadcast(IPAddress ipAddress, IPAddress subnetMask)
        {
            var ip = ipAddress.GetAddressBytes();
            var sub = subnetMask.GetAddressBytes();

            // 广播地址=子网按位求反 再 或IP地址
            for (var i = 0; i < ip.Length; i++)
            {
                ip[i] = (byte) ((~sub[i]) | ip[i]);
            }
            return new IPAddress(ip);
        }

 获取本机的广播地址。

        public static List<IPAddress> LocalBroadcasts
        {
            get
            {
                var lst = new List<IPAddress>();
                using (var moc = new ManagementClass("Win32_NetworkAdapterConfiguration").GetInstances())
                {
                    foreach (var item in moc)
                    {
                        using (item)
                        {
                            var ipArray = item["IPAddress"] as string[];
                            var subArray = item["IPSubnet"] as string[];

                            if (ipArray == null || subArray == null) continue;

                            for (var i = 0; i < ipArray.Length; i++)
                            {
                                var ipAddress = IPAddress.Parse(ipArray[i]);
                                var subAddress = IPAddress.Parse(subArray[i]);

                                if (ipAddress.IsIPv6LinkLocal) continue;

                                lst.Add(GetBroadcast(ipAddress, subAddress));
                            }

                        }
                    }
                }
                return lst;
            }
        }

 

版权声明:本文为mokeyish原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/mokeyish/p/5404153.html