Created
February 7, 2021 14:48
-
-
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
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 ( | |
"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