0

How would one get the master device of a network device they have an index of? I have looked into rtnetlink, but would prefer a simpler and more concise solution

Demiu
  • 97
  • 5
  • @larsks could you put that in an answer? Nobody else bothered to respond and I find this satisfactory. As an extra to anyone reading, if_indextoname can be used to get name from index – Demiu Jul 17 '23 at 08:47
  • 1
    I've moved my comment to an answer. – larsks Jul 17 '23 at 12:07

1 Answers1

1

Given the interface name you can read the value of /sys/class/net/<interface>/master. For example, on my system I have container with interface veth3c732e7. To find the associated bridge:

$ readlink /sys/class/net/veth3c732e7/master
../br-3d442aed4b81

We can confirm that information with the ip link command:

$ ip link show veth3c732e7
510: veth3c732e7@if509: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-3d442aed4b81 state UP mode DEFAULT group default
    link/ether 3e:66:b1:62:31:11 brd ff:ff:ff:ff:ff:ff link-netnsid 4

If you want to know how to do this without using /sys, the ip tool itself is open source. The relevant functions appear to be here and here; it involves sending a netlink message and then receiving and parsing the response.

larsks
  • 277,717
  • 41
  • 399
  • 399