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 
Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply