Created
June 30, 2022 05:45
-
-
Save iyashjayesh/1fff729cfad4baada1945e3102d5b0f1 to your computer and use it in GitHub Desktop.
Program to get the IP Address and Hostname
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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