Experts,
Please help me to write a script to find the network interface name from the given IPv6 address.
For example:
if "ifconfig" gives the output like:
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:90440 errors:0 dropped:0 overruns:0 frame:0
TX packets:90440 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:10181289 (10.1 MB) TX bytes:10181289 (10.1 MB)
eth0 Link encap:Ethernet HWaddr 00:50:56:bb:9f:9d
inet6 addr: fe80::250:56ff:febb:9f9d/64 Scope:Link
inet6 addr: 2001:111:1111:1111:1000::41/64 Scope:Global
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:138859 errors:0 dropped:10 overruns:0 frame:0
TX packets:69332 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:46310896 (46.3 MB) TX bytes:18119186 (18.1 MB)
eth1 Link encap:Ethernet HWaddr 00:50:56:bb:9f:9d
inet6 addr: fe80::250:56ff:febb:9f9d/64 Scope:Link
inet6 addr: 2001:222:2222:2222:1000::41/64 Scope:Global
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:138859 errors:0 dropped:10 overruns:0 frame:0
TX packets:69332 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:46310896 (46.3 MB) TX bytes:18119186 (18.1 MB)
and the given IPv6 address is: 2001:111:1111:1111:1000::41 then the output should be "eth0"
Appreciate your help in advance.
Thanks.
Why make things complicated? I like simple. And this is about as simple as it gets. (And you shouldn't be using ifconfig
as it's deprecated and not installed by default on modern Linux distributions.)
ip a s to fda8:75f3:eca7:100::1 | awk -F ": " 'NF > 1 {print $2}'
Let's go over it step by step.
First the ip
output.
$ ip address show to fda8:75f3:eca7:100::1
12: virbr2: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default qlen 1000
inet6 fda8:75f3:eca7:100::1/64 scope global
valid_lft forever preferred_lft forever
This tells us the interface the IP is on, and omits any other addresses that might be on the interface.
So we'll parse it out with awk
. We use ": "
as a field separator, print the second field, and only print matching lines.
$ ip address show to fda8:75f3:eca7:100::1 | awk -F ": " 'NF > 1 {print $2}'
virbr2
Finally we'll abbreviate address show
to the minimum.
$ ip a s to fda8:75f3:eca7:100::1 | awk -F ": " 'NF > 1 {print $2}'
virbr2
This will also work with IPv4 addresses, if you want to locate one of those.