gawk¶
Sorting IPv4 addresses¶
Function cmp_ip_addr¶
# cmp_ip_addr # For asort() to call # Compares IP addresses in values v1 and v1 function cmp_ip_addr (i1, v1, i2, v2, \ v1_octets, v2_octets) { #print "i1: " i1 ", v1: " v1 ", i2: " i2 ", v2: " v2 split(v1, v1_octets, ".") split(v2, v2_octets, ".") #print "v1_octets[4]: " v1_octets[4] ", v2_octets[4]: " v2_octets[4] if (v1_octets[1]+0 < v2_octets[1]+0) return -1 else if (v1_octets[1]+0 == v2_octets[1]+0) { if (v1_octets[2]+0 < v2_octets[2]+0) return -1 else if (v1_octets[2]+0 == v2_octets[2]+0) { if (v1_octets[3]+0 < v2_octets[3]+0) return -1 else if (v1_octets[3]+0 == v2_octets[3]+0) { if (v1_octets[4]+0 < v2_octets[4]+0) return -1 else if (v1_octets[4]+0 == v2_octets[4]+0) { return 0 } else return 1 } else return 1 } else return 1 } else return 1 }
Usage example¶
Addresses is an array with (FQDNs as indices and) IP addresses as values. Array networks is derived containing in ascending order all the unique /24 networks corresponding to the IP addresses from array Addresses.
# Create array of indices to Addresses in address order # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ addresses_n = asort(Addresses, addresses_sorted, "cmp_ip_addr")) # Create sorted list of /24 networks # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for (i = 1; i <= addresses_n; i++) { address = addresses_sorted[i] network = gensub(/\.[^.]+$/, "", 1, address) networks[network] = "" }