Search code examples
clinuxnetlink

Linux C get network interface's master interface


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


Solution

  • 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.