For IP address we can use the Net package. You can read all IP addresses using InterfaceAddrs, you need to filter out the loopback address to get real IP.
package main
import (
"fmt"
"net"
"os"
)
func main() {
//Reading the hostname using OS package.
hostname, err := os.Hostname()
if err != nil {
fmt.Println("Hostname: ", hostname)
}
//Reading IP Address
addrs, err := net.InterfaceAddrs()
if err == nil {
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
fmt.Println(ipnet.IP.String())
}
}
}
}
}
No comments:
Post a Comment