How can I fetch the ethernet port given the ip address? How can I fetch the ethernet port given the ip address? shell shell

How can I fetch the ethernet port given the ip address?


Replace 127.0.0.1 with the ip address you want to get the interface info for

ifconfig  | grep 127.0.0.1 -B1 | grep Link | cut -f 1 '-d '

If you also want to identify the physical port on the machine, run

ethtool -p $OUTPUT_OF_FIRST_COMMAND

It will blink the light on the ethernet card associated with that interface


A little messy but should work:

/sbin/ifconfig | grep -B1 1.2.3.4 | awk '{print $1; exit}'

Optionally, you could use the ip command which, when used with the -o|-oneline option, is a lot easier to parse. For example

ip -o addr | awk '/1.2.3.4/{print $2}'


Off the top of my head I might use grep:

ifconfig |grep -B1 '127.0.0.1' |grep -o '^[a-zA-Z0-9]*'  

Where '127.0.0.1' is the address you're looking for.

-B1 sets the number of lines preceding the match to return.

-o sets the second grep to only return the matching segment, instead of the whole line.

'^[a-zA-Z0-9]*' matches any alphanumerics that start at the beginning of the line.

Since ifconfig indents all lines except the interface name line, it will only match the interface name.

It's quick and dirty, but should work.