Go Program : Identify total number of network interfaces and display the details using index

Following example shows how to identify total number of available network interfaces and display its details using network packages InterfaceByIndex API.

 $ vim InterfaceByIndex.go 
package main
import (
        "net"
	"fmt"
	"log"
)

func main(){
	ifaces, err := net.Interfaces()
	if err != nil {
		log.Print(fmt.Errorf("localAddresses: %v\n", err.Error()))
		return
	}
	fmt.Println("Total interfaces : ", len(ifaces))

	for ifce_num := 1; ifce_num <= len(ifaces); ifce_num++ {
		netInterface, err := net.InterfaceByIndex(ifce_num)

		if err != nil {
			fmt.Println(err)
		}
		fmt.Println("Index: ", ifce_num, "interface", netInterface)
	}
}
 $ go build InterfaceByIndex.go 

$ ./InterfaceByIndex
Total interfaces : 3
Index: 1 interface &{1 65536 lo up|loopback}
Index: 2 interface &{2 1500 eth0 00:26:b9:11:51:48 up|broadcast|multicast}
Index: 3 interface &{3 1500 wlan0 0c:60:76:61:ce:49 up|broadcast|multicast}

OR you can run the program in single commands as,

 $ go run InterfaceByIndex.go 
Follow Lynxbee

Leave a Reply / Ask Question