Get Interface Name by Hardware Address
At work we have had a need for getting a interface name by mac address and are in a environment that doesn’t have many common Linux tools (nor would I want to regex it as the environment will constantly be changing).
My first solution was to to write a C program (about 125 lines) which used the linux/rtnetlink library. However, now that I’m looking at Golang I figured why not rewrite this (which is only about 40 lines).
Below is the code, hopefully the comments explain the solution.
package main
import (
"net"
"fmt"
"os"
)
func main() {
// First lets check our command line arguments and be sure we
// have a single input value which we will assume is mac_address.
args := os.Args
if len(args) != 2 {
panic("This binary takes a single argument of interface name.")
}
// Get a list of all interfaces on the machine.
interfaces, err := net.Interfaces()
if err != nil {
panic("Unable to get interfaces.")
}
// Loop over all interfaces
for i := range interfaces {
// Get the interfaces Index and then load
// the interface by Index.
id := interfaces[i].Index
inter, err := net.InterfaceByIndex(id)
if err != nil {
panic("Unable to get interface by id")
}
// If our command line input matches our HardwareAddr
// this is the MAC_ADDRESS you seek.
if args[1] == inter.HardwareAddr.String() {
fmt.Println(inter.Name)
}
}
}
And the code works something like this:
$ ./get_interface 12:34:56:78:90:00
en4