2

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 x.x.x.x y.y.y.y and it uses the first x.x.x.x to get the interface name, then makes $1 == $2 so then it can ping y.y.y.y 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.

FilBot3
  • 3,460
  • 6
  • 33
  • 55
  • 2
    Post some sample input (to the awk command) and expected output. – Ed Morton Aug 20 '13 at 17:17
  • 1
    possible duplicate of [How to fetch the logical name of a NIC card given the ip address associated with it ?](http://stackoverflow.com/questions/17476248/how-to-fetch-the-logical-name-of-a-nic-card-given-the-ip-address-associated-with) – jgb Aug 20 '13 at 17:23
  • Yes, I did duplicate post. I did not search correctly, and did not see that answer. It did work for me. I want to try these other suggestions as well. – FilBot3 Aug 20 '13 at 18:45

2 Answers2

3

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}'
iamauser
  • 11,119
  • 5
  • 34
  • 52
1

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

Jotne
  • 40,548
  • 12
  • 51
  • 55