Convert a Mac Address to a CIDR with Powershell

Convert a Mac Address to a CIDR with Powershell

Today, I needed to convert a mac address to a CIDR. The lesson I learned about this is to go back to the basics instead of looking around for a quick answer. So, to the basics first.

A mac address is a 4 octet number that represents a binary position. It ranges between 1 and 255. This means something like 255.255.255.0 is represented in binary as: 1111 1111 1111 1111 1111 1111 0000 0000

It’s easier to remember the 255 number instead of all those ones and zeros. However, what’s that CIDR? Well, what’s a CIDR? A CIDR represents the mac address and how many positions there are. If you count the number above, it turns into 24 1s and 8 0s. Thus the CIDR is 24. Very simple.

Now, how do you change 240.0.0.0 to a cidr? You can go to a chart and look or we can use PowerShell. The first thing we need to do is split up this string.

"240.0.0.0" -split '\.' 

We split the string up with a split command and tell it to split it up by the . item. We use an exit \ because the . is a special character for regex. Next, we loop through this list of octets with a foreach-object loop.

$Mask -split '\.' | ForEach-Object {
        
    }

Then we break down each octet into a binary number. We do this with a system.convert and tell it the number we bytes we want which is 2.

[System.Convert]::ToString($_, 2)

We then pad that information because sometimes 0s will produce more useless items.

([System.Convert]::ToString($_, 2).PadLeft(8, '0'))

The code above will give us the 1s and 0s of the binary number. Now we need to count the ones. We do this by converting the string to a char array with at .toochararray(). We search the string with a where-object for the number 1 and finally count it.

(([System.Convert]::ToString($_, 2).PadLeft(8, '0')).tochararray() | where-object { $_ -eq '1' } | measure-object).count

Now we need to add each item up. We do this by adding a variable before the loop set to 0 and then add the variable to the variable and the count. Finally, after the loop, display the information.

$Cidr = 0
    $Mask -split '\.' | ForEach-Object {
        $Cidr = $Cidr + (([System.Convert]::ToString($_, 2).PadLeft(8, '0')).tochararray() | where-object { $_ -eq '1' } | measure-object).count
    }
    $Cidr

That’s it yall! We count the number of 1s. That will give us our cidr count.

Script

Have fun with the script!

function ConvertFrom-SHDIPv4MaskToCidr {
    param (
        [string]$Mask
    )
    $Cidr = 0
    $Mask -split '\.' | ForEach-Object {
        $Cidr = $Cidr + (([System.Convert]::ToString($_, 2).PadLeft(8, '0')).tochararray() | where-object { $_ -eq '1' } | measure-object).count
    }
    $Cidr
}
SHD – Set Mac Structure

SHD – Set Mac Structure

I hate it when you get a mac address that’s not in the right format. Last week I got the mac address XX-XX-XX-XX when I needed to input it as XX:XX:XX:XX. So aggravating. So, here comes PowerShell to help. First, let’s validate the mac address. Second, let’s change out the pattern, and finally, we display the information.

Validate Mac Address

To validate a mac address we need to use a regex. I like the input to validate the pattern for us.

[parameter(Mandatory = $True)][ValidatePattern("^([0-9A-Fa-f]{2}[: \.-]){5}([0-9A-Fa-f]{2})$")][string]$MacAddress,

Let’s take a look at the validate pattern. ^([0-9A-Fa-f]{2}[: .-]){5}([0-9A-Fa-f]{2})$ The [0-9A-Fa-f] searches or the number 0-9, all the letters A,B,C,D,E,F, and the letters a,b,c,d,e,f. {2} states to look for only two of these characters. [: .-] is the next few characters we are searching for. This is the separator area of the mac address. xx:xx. From here we make sure all of this is repeated 5 times. Thus we need to make sure it’s grouped together using the preferences. ([0-9A-Fa-f){2}[: .-]). Now, this is grouped together, we want it to repeat 5 times. We don’t want it to repeat every time because the last subset does not have a separator. We do this using {5} after our group. Finally, we ask for the same thing again. ([0-9A-Fa-f]{2}). We finish it off with $.

Editing the Separators

Now we have our mac address validated we need to start building a way to replace the separators. First we need to setup the patter like above.

$Pattern = '[0-9A-Fa-f]'

Now this is the patter we are gong to look for. We want all the 0 – 9, A,B,C,D,E,F,a,b,c,d,e,f.

$Mac = $MacAddress -replace $Pattern, $Seperator

With this command we are taking the validated mac address, searching for the patter, and replacing the separators with the provided separator. Next, we can uppercase or lower case the mac address using $Mac.ToUpper() or $Mac.ToLower().

The Script

Below is the script that will make life easier for everyone. Notice, I gave the option to add the output to the clipboard.

function Set-SHDMacAddressStructure {
    [cmdletbinding()]
    param (
        [parameter(Mandatory = $True)][ValidatePattern("^([0-9A-Fa-f]{2}[: \.-]){5}([0-9A-Fa-f]{2})$")][string]$MacAddress,
        [parameter(Mandatory = $true)][String]$Seperator,
        [Parameter(HelpMessage = "Changes the case")][Validateset("UpperCase", "LowerCase")]$Case,
        [parameter(helpmessage = "Added mac to clipboard")][switch]$ToClipboard
    )
    $Pattern = '[^a-zA-Z0-9]'
    $Mac = $MacAddress -replace $Pattern, $Seperator
    if ($case -eq "UpperCase") {
        if ($ToClipboard) {
            $Mac.ToUpper() | clip 
            $Mac.ToUpper()
        } else {
            $Mac.ToUpper()
        }
    }
    elseif ($case -eq "LowerCase") {
        if ($ToClipboard) {
            $Mac.ToLower() | clip 
            $Mac.ToLower()
        } else {
            $Mac.ToLower()
        }
    }
    else {
        if ($ToClipboard) {
            $Mac | clip 
            $Mac
        } else {
            $Mac
        }
    }
}