Skip to content

Instantly share code, notes, and snippets.

@ihipop
Last active March 31, 2023 02:59
Show Gist options
  • Save ihipop/626eed22ea59e12373c3df0ef9a28025 to your computer and use it in GitHub Desktop.
Save ihipop/626eed22ea59e12373c3df0ef9a28025 to your computer and use it in GitHub Desktop.
Shell Script to Manipulate NETMASK/CIDR
#!/bin/bash
# from https://stackoverflow.com/questions/20762575/explanation-of-convertor-of-cidr-to-netmask-in-linux-shell-netmask2cdir-and-cdir
# see also https://gist.github.com/RichardBronosky/7902f062ab36d3c99413ba21986ed0cb
mask2cdr ()
{
# 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) ))
}
cdr2mask ()
{
# 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}
}
function join_by {
local d=${1-} f=${2-}
if shift 2; then
printf %s "$f" "${@/#/$d}"
fi
}
JS=()
while read -r LINE || [ -n "$LINE" ]; do
JS+=('{
"val": "'"$LINE"'",
"note": "CN"
}')
done <<< "$(grep ' bypass4' ipset.conf |awk '{print $3}')"
join_by ',' "${JS[@]}"
JS=()
while read -r LINE || [ -n "$LINE" ]; do
#echo "$LINE";
IFS='/' read -ra ARR <<< "$LINE"
NET=${ARR[0]}
MASK=${ARR[1]}
CIDR=$(mask2cdr "$MASK")
JS+=('{
"val": "'"$NET"/"$CIDR"'",
"note": "NCN"
}')
done <<< "$(awk '{print $3}' < cn-no-route1.txt)"
join_by ',' "${JS[@]}"
no-route = 1.0.0.0/255.128.0.0
add bypass4 140.237.0.0/16 comment "force-bypass-ips"
@ihipop
Copy link
Author

ihipop commented Mar 31, 2023

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