Skip to content

Instantly share code, notes, and snippets.

@iyashjayesh
Created June 30, 2022 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iyashjayesh/1fff729cfad4baada1945e3102d5b0f1 to your computer and use it in GitHub Desktop.
Save iyashjayesh/1fff729cfad4baada1945e3102d5b0f1 to your computer and use it in GitHub Desktop.
Program to get the IP Address and Hostname
package main
import (
"log"
"net"
"os"
)
func main() {
hostname, _ := os.Hostname() // get hostname
addrs, err := net.LookupIP(hostname) // returns a slice of the IP addresses of the host
// lookupIP looks up host using the local resolver. It returns a slice of that host's IPv4 and IPv6 addresses.
if err != nil {
log.Println("Failed to detect machine host name. ", err.Error())
return
}
log.Println("All Addrs: ", addrs)
var ip string
for _, addr := range addrs {
if ipv4 := addr.To4(); ipv4 != nil {
// only take the class B address
if ipv4[0] == 172 {
ip = ipv4.String()
break
}
}
}
log.Println("Host name: ", hostname)
log.Println("IP: ", ip)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment