简体   繁体   中英

Retrieve the name of a Network Interface using an IP Address and AWK Bash

I am trying to use Bash on CentOS 6.4 to retrieve the network interface name attached to an IP address using AWK. I have a bit of command from a Solaris box, but I'm not sure how to convert it to Linux output.

The command looks like this:

ifconfig -a | awk '
    $1 ~ /:/    {split($1,nic,":"); 
                     lastif=sprintf("%s:%s",nic[1],nic[2]);}
    $2 == "'$1'"    { print lastif ; exit; }

    '

Its part of a script, so it takes commandline argument like monitor.sh xxxx yyyy and it uses the first xxxx to get the interface name, then makes $1 == $2 so then it can ping yyyy later. I'm guessing that in Solaris the ifconfig -a output is different than CentOS. I can get the interface name if the IP and interface are on the same line, but in linux, they're on two different lines. Any ideas.

I don't have CentOS, but in RHEL, IP address is listed as inet address. I believe they should be same.

The following command should give you the interface name which has a IP address.

export iface=$(ifconfig | grep -B1 "inet addr:x.x.x.x" | awk '$1!="inet" && $1!="--" {print $1}')

echo "$iface" # To get the interface name for x.x.x.x ip

And this one should show the IP including localhost :

ifconfig | grep "inet addr:" | sed -e 's/addr:/addr: /g' | awk '{print $3}'

geting ifname for 127.0.0.1 (or any other IP)

ifconfig | awk '/127.0.0.1/ {print $1}' RS="\n\n"
lo

getting ip:

ifconfig | awk -F"[ :]+" '/inet addr:/ {print $4}'

Post the output of ifconfig, and I can help you fine tune for your OS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM