public static IPAddress GetBroadcast(IPAddress ipAddress, IPAddress subnetMask)
{
var ip = ipAddress.GetAddressBytes();
var sub = subnetMask.GetAddressBytes(); // 广播地址=子网按位求反 再 或IP地址
for (var i = ; 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 = ; 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;
}
}