interface_information.sh 2.5 KB
##
# retrieve interfaces. I prefer using ip if it is
# available, else I fallback to ifconfig... don't know
# how to retrieve this information on other systems.
# This also exports the environment variables.
#
gather_interface_info() {
	[ -z "${NINTERFACES}" ] || return

	local NO=1

	if [ ${IP} ]
	then
		gather_if_info_ip
	else
		if [ ${IFCONFIG} ]
		then
			gather_if_info_ifconfig
		else
			${LOGGER} -p local0.warn 'Found no way to retrieve interface information.'
		fi
	fi

	export NINTERFACES

	while [ ${NO} -le ${NINTERFACES:=0} ]
	do
		export IF${NO}_NAME IF${NO}_MAC IF${NO}_STATE IF${NO}_IPV4 IF${NO}_IPV6
		NO=$((NO+1))
	done
}

##
# get the interface information from the ip tool
#
gather_if_info_ip() {
	eval $(${IP} -o link | ${AWK} '{
		sub(/:/,"",$1);
		no=$1;
		sub(/:/,"",$2);
		name=$2;
		classes=classes "net_iface_" name " ";
		for (i=3; i<NF; i++) {
			if ($i == "state") {
				i++; state=$i
			}
			if ($i ~ /link/) {
				i++; mac=$i;
				classes=classes mac " "
			}
		}
		print "IF" no "_NAME=" name ";IF" no "_STATE=" state ";IF" no "_MAC=" mac ";";
		if ("UP" == state) classes=classes mac " "
	}
	BEGIN {
		classes=""
	}
	END {
		print "set_class " classes ";";
		print "NINTERFACES=" FNR ";"
	}')

	eval $(${IP} -o addr | ${AWK} '{
		sub(/:/,"",$1);
		no=$1;
		if ($3 == "inet") {
			sub(/[\/%].*/,"",$4);
			print "IF" no "_IPV4=\"${IF" no "_IPV4}" $4 " \";";
			classes=classes $4 " "
		}
		if ($3 == "inet6") {
			sub(/[\/%].*/,"",$4);
			print "IF" no "_IPV6=\"${IF" no "_IPV6}" $4 " \";";
			classes=classes $4 " "
		}
	}
	BEGIN {
		classes=""
	}
	END {
		print "set_class " classes ";"
	}')
}

##
# get interface data via the ifconfig tool
# FIXME This is outdated. It does not set classes at all.
#
gather_if_info_ifconfig() {
	eval $(${IFCONFIG} -a | ${AWK} '
	/ether/ { mac=$2 }
	/inet / { ipv4=ipv4 $2 " " }
	/inet6/ { ipv6=ipv6 $2 " " }
	/^[^ \t]/ {
		if ("" != ipv4 || "" != ipv6) state="UP"; else state="DOWN";
		if ("" != name) {
			print "IF" no "_NAME=" name ";IF" no "_STATE=" state ";IF" no "_MAC=" mac ";" \
				"IF" no "_IPV4=\"${IF" no "_IPV4}" ipv4 " \";" \
				"IF" no "_IPV6=\"${IF" no "_IPV6}" ipv6 " \";";
			no++;
		}
		ipv4=ipv6="";
		sub(/:/,"",$1);
		name=$1
	}
	BEGIN {
		no=1;
	}
	END {
		if ("" != ipv4 || "" != ipv6) state="UP"; else state="DOWN";
		print "IF" no "_NAME=" name ";IF" no "_STATE=" state ";IF" no "_MAC=" mac ";" \
			"IF" no "_IPV4=\"${IF" no "_IPV4}" ipv4 " \";" \
			"IF" no "_IPV6=\"${IF" no "_IPV6}" ipv6 " \";";
		print "NINTERFACES=" no
	}')
}

# vim: set ts=4 sw=4: