Skip to content

Instantly share code, notes, and snippets.

@gibson042
Created January 14, 2021 00:21
Show Gist options
  • Save gibson042/38c6f919012dcec21b41ebb666051a8c to your computer and use it in GitHub Desktop.
Save gibson042/38c6f919012dcec21b41ebb666051a8c to your computer and use it in GitHub Desktop.
Use awk to implement `ip route`-like behavior
#!/bin/sh
awk '
BEGIN { OFS="\t"; HEX_LOWER="0123456789abcdef" }
FILENAME ~ /trie$/ { if($0 ~ "/32 host") ADDRS[ipv4_decimal_to_bits(prev)]=prev; prev=$2; next }
FNR==1 { print $1, $2, $3, $8, "Source"; next }
{
iface=$1; dest=hex_reverse_octets($2); gateway=hex_reverse_octets($3); mask=hex_reverse_octets($8);
source_guess=lookup_by_longest_prefix(ADDRS, apply_bitmask(hex_to_bits(dest), hex_to_bits(mask)));
print iface, ipv4_hex_to_decimal(dest), ipv4_hex_to_decimal(gateway), ipv4_hex_to_decimal(mask), source_guess;
}
function lookup_by_longest_prefix(map, key, _, k) {
while(1) {
for(k in map) if(substr(k, 1, length(key))==key) return map[k];
key=substr(key, 1, length(key)-1);
}
return ""
}
function ipv4_hex_to_decimal(hex, _, s, i) {
for(i=1; i<8; i+=2) s=sprintf("%s.%d", s, hex_to_uint(substr(hex, i, 2)));
return substr(s, 2, length(s)-1);
}
function ipv4_decimal_to_bits(addr, _, bits, octets, i) {
split(addr, octets, "[.]");
for(i=1; i<=4; i++) bits=bits hex_to_bits(sprintf("%02X", octets[i]));
return bits;
}
function apply_bitmask(base, mask, _, bits, i) {
for(i=length(base); i>=1; i--) bits=(substr(base, i, 1) * substr(mask, i, 1)) bits;
return bits;
}
function hex_reverse_octets(hex, _, r, i) {
for(i=length(hex)-1; i>=1; i-=2) r=r substr(hex, i, 2);
return r;
}
function hex_to_bits(hex, _, bits, i, h, t, b) {
for(i=1; i<=length(hex); i++) {
h=hex_to_uint(substr(hex, i, 1));
for(t=8; t>=1; t/=2) {
b=(h>=t);
if(b) h-=t;
bits=bits b;
}
}
return bits;
}
function hex_to_uint(hex, _, n, i) {
for(i=1; i<=length(hex); i++) n=n*16 + index(HEX_LOWER, tolower(substr(hex, i, 1)))-1;
return n;
}
' /proc/net/fib_trie /proc/net/route
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment