Print details of network interface ( IP address, mac, status etc ) using go language program

 $ vim networkInterfaceDetails.go 
package main

import (
    "fmt"
    "log"
    "net"
    "strings"
)

func networkInterfaceDetails() {
	var count int

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

	for _, i := range ifaces {
		addrs, err := i.Addrs()
		if err != nil {
			log.Print(fmt.Errorf("localAddresses: %v\n", err.Error()))
			continue
		}

		for _, a := range addrs {
			log.Printf("Index:%d Name:%v addr:%v, mac:%v\n", i.Index, i.Name, a, i.HardwareAddr )
			if strings.Contains(i.Flags.String(), "up") {
				fmt.Println("Status : UP")
			} else {
				fmt.Println("Status : DOWN")
			}
		}
		count++
	}
	fmt.Println("Total interfaces : ", count)
}

func main() {
    networkInterfaceDetails()
}

Now, we can compile the go program as,

 $ go build networkInterfaceDetails.go 

and execute as,

 $ $ ./networkInterfaceDetails 
2018/09/04 09:01:23 Index:1 Name:lo addr:127.0.0.1/8, mac:
Status : UP
2018/09/04 09:01:23 Index:1 Name:lo addr:::1/128, mac:
Status : UP
2018/09/04 09:01:23 Index:3 Name:wlan0 addr:192.168.0.109/24, mac:0c:60:76:61:ce:49
Status : UP
2018/09/04 09:01:23 Index:3 Name:wlan0 addr:fe80::a2ca:2820:a122:7db4/64, mac:0c:60:76:61:ce:49
Status : UP
Total interfaces :  3

You can also build and run the program in one commands as,

 $ go run networkInterfaceDetails.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