Search code examples
c#powershellsubnet

Calculate directed broadcast address given IP address and subnet in PowerShell


My goal is to calculate the directed broadcast address when given the IP and subnet mask of a host node. I know, sounds like homework. Once I reasoned through my task and boiled it down to this, I was amused with myself. Anyway, the solution will look something like the one in this question I suppose, but I'm not a math major and my C sucks. I could do with a PowerShell (preferred) or C# example to get me going.

thanks!


Solution

  • Here is mine which uses Get-NetIPAddress from NetTCPIP and IPAddress from the System.Net:

    $NetIPAddress = Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex 25
    [Net.IPAddress]::new((
        (
            [Net.IPAddress]::Parse($NetIPAddress.IPAddress).Address -band
            [uint]::MaxValue -shr (32 - $NetIPAddress.PrefixLength)
        ) -bor (
            [uint]::MaxValue -shl $NetIPAddress.PrefixLength
        )
     )).IPAddressToString