I'm maintaining a bash script that runs on RHEL 5. Given an domain name, I want to ensure that there is an interface on the current machine listening to the expected IP address.
# Check that the IP is bound to this host, to avoid running on the wrong machine.
IP=$(dig +short ${EXPECTED_SUBDOMAIN}.example.com | tail -n 1)
if ! $(/sbin/ifconfig 2>/dev/null | /bin/grep -q $IP) ; then
echo "IP for ${EXPECTED_SUBDOMAIN} ($IP) doesn't appear to be on this host"
exit 1
fi
This breaks when IP addresses are substrings of each other. If my expected IP address is 1.2.3.4
, it doesn't exit if the machine has an IP address (or even subnet mask!) of 11.2.3.4
or 1.2.3.40
.
The only solution I can see is grep "inet addr:${IP} "
but it seems dirty to search for other text.
Is there are more robust way to find out the IP addresses of interfaces (without getting confused by things like subnet masks) and compare them? Is there a better approach?