Skip to content

Instantly share code, notes, and snippets.

@kwilczynski
Last active November 24, 2023 13:31
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save kwilczynski/5d37e1cced7e76c7c9ccfdf875ba6c5b to your computer and use it in GitHub Desktop.
Save kwilczynski/5d37e1cced7e76c7c9ccfdf875ba6c5b to your computer and use it in GitHub Desktop.
CIDR to netmask in bash.
# Return netmask for a given network and CIDR.
cidr_to_netmask() {
value=$(( 0xffffffff ^ ((1 << (32 - $1)) - 1) ))
echo "$(( (value >> 24) & 0xff )).$(( (value >> 16) & 0xff )).$(( (value >> 8) & 0xff )).$(( value & 0xff ))"
}
@ckuhtz
Copy link

ckuhtz commented Oct 11, 2023

Cool. But why $2 and not $1? :)

@kwilczynski
Copy link
Author

@ckuhtz, I copied this from a larger script of mine, just to memoize it here for my future reference, and where there was something else there to do. But that was many years ago, and I don't quite remember. 😄 Fixed now! Thank you!

@ckuhtz
Copy link

ckuhtz commented Oct 11, 2023

Awesome! 👏🏻😀 very useful.

@kwilczynski
Copy link
Author

@ckuhtz, I am glad you found it useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment