Skip to content

Instantly share code, notes, and snippets.

@xrat
Last active February 2, 2025 12:13
Show Gist options
  • Save xrat/ac7b4319cbb6dd5779f695ecacd53518 to your computer and use it in GitHub Desktop.
Save xrat/ac7b4319cbb6dd5779f695ecacd53518 to your computer and use it in GitHub Desktop.
rgrepcidr.awk - Print IPs that match networks in CIDR notation
#!/usr/bin/gawk -f
#
# Print IP addresses that match networks in CIDR notation
#
# rgrepcidr[.awk] * 2025-02-02 (c) Andreas Schamanek
#
# @author Andreas Schamanek <https://andreas.schamanek.net>
# @license GPL <https://www.gnu.org/licenses/gpl.html>
#
# The script supports 3 output styles by setting variable "output":
# IP and network (0), IP only (1), network only (2)
#
# Example: rgrepcidr -v cidrfile=list_of_cidrs -v output=2 <<< 127.2.3.4
function printresult(ip, cidr) {
if (0+output == 0) {
print ip, cidr
} else if (0+output == 1) {
print ip
} else if (0+output == 2) {
print cidr
}
}
function ip2dec(ip, a) {
split(ip,a,".")
return ((a[1]*256+a[2])*256+a[3])*256+a[4]
}
BEGIN {
ip4regex="^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])\\.){3}(25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])$"
while((getline < cidrfile) >0) {
split($1,a,"/")
net=a[1]
mask=a[2]
if (net !~ ip4regex) {
print "ERROR: net " net " is not a valid IPv4 address" > "/dev/stderr"
exit(1)
}
if (mask == "") mask=32
if (0+mask == 0 || mask > 32) {
print "ERROR: mask /" mask " is invalid" > "/dev/stderr"
exit(1)
}
shift = lshift(0xffffffff,32-mask); shift = and(0xffffffff,shift)
net = and(ip2dec(net),shift)
cidrs[shift][net] = $1
}
close(cidrfile)
# set order of processing of cidrs from larger to smaller ranges
PROCINFO["sorted_in"] = "@ind_num_asc";
}
# input other than quad-dotted IPv4 addresses is ignored
$1 ~ /^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])\.){3}(25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])$/ {
ip=$1
# look for already processed IPs
if (cached[ip]) {
if (cached[ip] != "-") {
printresult(ip, cached[ip])
}
next
}
ipdec = ip2dec(ip)
cidr = ""
for(shift in cidrs) {
ipnet = and(ipdec, shift)
if (cidrs[shift][ipnet]) break
}
cidr=cidrs[shift][ipnet]
if (cidr) {
cached[ip] = cidr
printresult(ip, cidr)
} else {
cached[ip] = "-"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment