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

1.3k views Asked by At

I am trying to write a bash script to fetch the ethernet port of an interface whose IP address I know. I need to grab this from ifconfig but can't seem to be able to figure out how to go about it. Any ideas?

Thanks.

4

There are 4 answers

0
Shawn Chin On BEST ANSWER

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}'
0
Nick On

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

0
d_b On

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.

0
kurumi On
ifconfig | awk 'BEGIN{RS=""}/127.0.0.1/{print $1}'

ifconfig | ruby -00 -ane 'puts $F[0] if /127.0.0.1/'