首页 > 代码库 > C#获得广播地址

C#获得广播地址

using System.Net;
/// <summary>
/// 获得广播地址
/// </summary>
/// <param name="ipAddress">IP地址</param>
/// <param name="subnetMask">子网掩码</param>
/// <returns>广播地址</returns>
public static string GetBroadcast(string ipAddress, string subnetMask)
{

byte[] ip = IPAddress.Parse(ipAddress).GetAddressBytes();
byte[] sub = IPAddress.Parse(subnetMask).GetAddressBytes();

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