Skip to content

Instantly share code, notes, and snippets.

@ik5
Created February 7, 2021 14:48
Show Gist options
  • Save ik5/1c99a1edfc26faac0f8167ea13e9cfea to your computer and use it in GitHub Desktop.
Save ik5/1c99a1edfc26faac0f8167ea13e9cfea to your computer and use it in GitHub Desktop.
Example for getting machine hostname and all of it's IP numbers based on local devices
package main
import (
"fmt"
"net"
"os"
"strings"
)
// GetMachineInfo return a list of:
// 1. Server Name
// 2. All IP numbers based on network device
//
// If something is wrong, an error is returned instead
func GetMachineInfo() ([]string, error) {
list := []string{}
name, err := os.Hostname()
if err != nil {
return nil, err
}
list = append(list, name)
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
list = append(list, ip.String())
}
}
return list, nil
}
func main() {
list, err := getMachineInfo()
if err != nil {
panic(err)
}
fmt.Println(strings.Join(list, ", "))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment