Skip to content

Instantly share code, notes, and snippets.

@ik5
Created Feb 7, 2021
Embed
What would you like to do?
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