子网和IP地址ANDing尾随0' s

时间:2017-06-05 18:46:40

标签: powershell binary ipv4 subnet

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

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才能执行正确的AND操作?

1 个答案:

答案 0 :(得分:7)

通常更容易使用[IPAddress]课程。例如:

$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。

我写的一篇文章中提供了完整的文章和更多功能:

Windows IT Pro - Working with IPv4 Addresses in PowerShell