Home » Programming Languages » Go Language Programs » Print details of network interface ( IP address, mac, status etc ) using go language program

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 

Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment