Forked from rsperl/convert_between_cidr_and_netmask.sh
Created
September 24, 2020 07:40
-
-
Save aachyee/7190fbc24531c509709e93418bd396dc to your computer and use it in GitHub Desktop.
convert between cidr and netmask
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # src: https://stackoverflow.com/questions/20762575/explanation-of-convertor-of-cidr-to-netmask-in-linux-shell-netmask2cdir-and-cdir | |
| mask2cidr () | |
| { | |
| # Assumes there's no "255." after a non-255 byte in the mask | |
| local x=${1##*255.} | |
| set -- 0^^^128^192^224^240^248^252^254^ $(( (${#1} - ${#x})*2 )) ${x%%.*} | |
| x=${1%%$3*} | |
| echo $(( $2 + (${#x}/4) )) | |
| } | |
| cidr2mask () | |
| { | |
| # Number of args to shift, 255..255, first non-255 byte, zeroes | |
| set -- $(( 5 - ($1 / 8) )) 255 255 255 255 $(( (255 << (8 - ($1 % 8))) & 255 )) 0 0 0 | |
| [ $1 -gt 1 ] && shift $1 || shift | |
| echo ${1-0}.${2-0}.${3-0}.${4-0} | |
| } | |
| # cidr2mask 16 => 255.255.0.0 | |
| # mask2cidr 255.255.0.0 => 16 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment