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 (

func main(){
	ifaces, err := net.Interfaces()
	if err != nil {
		log.Print(fmt.Errorf("localAddresses: %v\n", err.Error()))
	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("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 
Android Android Commands Android Java Applications Application Libraries Application Stack / User Interface Bash / Shell Scripts Commands and Packages Compilation Content Management System - CMS Core Kernel C Programs Development & Build Development Environment Setup Errors & Failures Flutter git Go Language Programs Hardware Platforms HTML JAVA Programs Kernel & Device Drivers Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Monetization / Google AdSense NDK / Middleware / HAL OS Concepts PHP Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized User Interface Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply / Ask Question