user11684966
user11684966

Reputation:

Shell - Get interface name of IP address

Is there a way to query for the interface name of and IP address on Linux (GNU)? Vice versa this seems to be simple but I need it exactly the other way around, as I just have one IP address as input which is assigned to one of many interfaces of my system. How do I find out to which interface the input IP address belongs to?

imagin you have a script like that:

ips=($(hostname -I))

PS3='Please select a network the master should listen onto: '
ips=($(hostname -I))
ips=("${ips[@]}" 'Quit')
select ip in "${ips[@]}"; do
  case $ip in
    *[0-9]*)
      break
      ;;
    Quit) echo quit
      break;;
    *) echo Invalid option >&2;;
  esac
done

echo "IP: $ip has been choosen for enrollment"

And now you want to know the interface name of the selected ip address

Thanks in advance

Upvotes: 1

Views: 1596

Answers (1)

larsks
larsks

Reputation: 311605

You can parse the output of ip addr using e.g. awk to find the interface name that has a certain ip address. For example:

ip addr | awk -vtarget_addr=192.168.1.200 '
/^[0-9]+/ {
  iface=substr($2, 0, length($2)-1)
}

$1 == "inet" {
  split($2, addr, "/")
  if (addr[1] == target_addr) {
    print iface
  } 
}
'

This look for the interface with address 192.168.1.200. On my system, this will print:

vlan100

Because:

$ ip addr show vlan100
5: vlan100: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN group default qlen 1000
    link/ether 56:ba:dc:0f:73:69 brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.200/32 brd 192.168.1.200 scope global noprefixroute vlan100
       valid_lft forever preferred_lft forever
    inet 192.168.1.169/24 brd 192.168.1.255 scope global dynamic noprefixroute vlan100
       valid_lft 47960sec preferred_lft 47960sec
    inet6 fe80::acb6:be79:224e:3062/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever

Upvotes: 1

Related Questions