Go program to display IP address details of a network interface using interface name

If we want to know the IPv4 and IPv6 addresses of certain network interface using go language, we need to use network packages InterfaceByName API as,

 $ vim ipaddress.go 
package main
import (
        "net"
        "log"
        "fmt"
)

func main(){
        ief, err := net.InterfaceByName("wlan0")
        if err !=nil{
                log.Fatal(err)
        }
        addrs, err := ief.Addrs()
        if err !=nil{
                log.Fatal(err)
        }
        fmt.Println(addrs[0])
        fmt.Println(addrs[1])
}
 $ go build ipaddress.go 
 $ ./ipaddress 
192.168.0.109/24
fe80::a2ca:2820:a122:7db4/64

OR in a single command, you can execute as,

 $ go run ipaddress.go 

Leave a Comment