子网和 IP 地址与尾随 0

Subnet and IP address ANDing trailing 0's

所以我有一个脚本,用于对 IPv4 地址和子网地址进行 ANDing。不检查它是否是有效输入(我应该添加),它将输入转换为二进制。

if ($readInput -match "y"){
    $readIP = read-host "Please input an IPv4 address to be ANDed " 

    # need to add subnet mask later. 
    $readSub = read-host "Please input the Subnet Mask "


    #need to delimite '.'
    #$readIP.split "."
    #$readSub.split "."

    #need to join them

    #convert IPv4 address to binary, period seperated at each octet. (input ip, base 2)
    $binIP = [convert]::ToString($readIP,2)
    write-host "$binIP" -backgroundcolor "white" -foregroundcolor "black"
    ## need to have two 32 element array that compares each 1 and 0. loop through each one with a counter and compare them with
    ## conditional if statements

    #conditional statements for /cider notion to equal a binary number (mask, base 2)
    $binSub = [convert]::ToString($readSub,2)
    write-host "$binSub" -backgroundcolor "white" -foregroundcolor "black"
}

输入为:

19216823
2552552550

输出为:

1001001010011100110110111
10011000001001001101110001100110

我是否必须在 IP 地址末尾添加 7 个尾随 0 才能执行正确的 ANDing?

通常使用 [IPAddress] class 更容易。示例:

$ip = [IPAddress] "192.168.32.76"
$networkMask = [IPAddress] "255.255.255.0"
$networkID = [IPAddress] ($ip.Address -band $networkMask.Address)
$networkID.IPAddressToString  # outputs "192.168.32.0"

如果要计算网络掩码字符串中的位数,可以使用如下函数:

function ConvertTo-IPv4MaskBits {
  param(
    [parameter(Mandatory=$true)]
    [String] $MaskString
  )
  $mask = ([IPAddress] $MaskString).Address
  for ( $bitCount = 0; $mask -ne 0; $bitCount++ ) {
    $mask = $mask -band ($mask - 1)
  }
  $bitCount
}

此函数假设网络掩码 ID 格式正确。

我不久前写的一篇文章中提供了完整的说明和更多功能:

IT Pro Today - Working with IPv4 Addresses in PowerShell