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

In this post, we will write a simple golang program which can print the IP address, mac, network status etc on Linux machine for the network interface.

 $ 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 

lynxbee_ezoic

Subscribe with Valid Email Id to receive updates in Inbox. ( Secured by Google FeedBurner )

   


Leave a Comment

Android Android Applications Android Build system Android Commands Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development & Build Development, Debugging and Performance Tools Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia Audio, Video, Images NDK / Middleware / HAL OS Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web design and development Website Hosting Wordpress Yocto / Bitbake / Openembedded