Get interface addresses in a scriptable format in Linux

Preface

I noticed it's annoyingly difficult to get the IP addresses assigned to your network interfaces for scripting purposes.

I ended up writing the fairly simple one-liner below that lists all IPv4 addresses (change -4 to -6 for IPv6) in the format "interface-address", e.g. "eth0-192.168.1.1".

It also ignores the loopback address since that's generally quite irrelevant.

I personally used this to check which interfaces a certain program was communicating over and send me alerts if it uses the wrong interface.

Code

ip -o -4 addr show | grep -v '127.0.0.1' | awk '{print $2"-"$4}' | cut -d'/' -f1

You can then use this in your scripts for something like:

eth0ip=$(ip -o -4 addr show | grep -v '127.0.0.1' | awk '{print $2"-"$4}' | cut -d'/' -f1 | grep 'eth0-' | cut -d'-' -f2)

This is the end result script, without the action I implemented later when "illegal" connections were detected.

#!/usr/bin/env bash

# Which program to check for
program="httpd"

# Which interface to check for
interface="eth0"

# Find the IP address for the interface
interfaceip=$(ip -o -4 addr show | grep -v '127.0.0.1' | awk '{print $2"-"$4}' | cut -d'/' -f1 | grep "${interface}-" | cut -d'-' -f2)

echo "Interface ${interface} IP address is ${interfaceip}"

# Check how many connections the program has with the eth0 IP address
connections=$(netstat -4 -6 -plan 2>&1 | grep "/${program}" | grep "${interfaceip}" | wc -l)

echo "${program} has ${connections} open connections on interface ${interface}"

if [ ${connections} -gt 0 ]; then
	echo "${program} has connections on interface ${interface}, but it shouldn't. Bad ${program}."
	exit 1
fi

echo "No connections from ${program} on interface ${interface}"

exit 0