获取机器mac/ip

  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. )
  6. func getMacAddrs() (macAddrs []string) {
  7. netInterfaces, err := net.Interfaces()
  8. if err != nil {
  9. fmt.Printf("fail to get net interfaces: %v", err)
  10. return macAddrs
  11. }
  12. for _, netInterface := range netInterfaces {
  13. macAddr := netInterface.HardwareAddr.String()
  14. if len(macAddr) == 0 {
  15. continue
  16. }
  17. macAddrs = append(macAddrs, macAddr)
  18. }
  19. return macAddrs
  20. }
  21. func getIPs() (ips []string) {
  22. interfaceAddr, err := net.InterfaceAddrs()
  23. if err != nil {
  24. fmt.Printf("fail to get net interface addrs: %v", err)
  25. return ips
  26. }
  27. for _, address := range interfaceAddr {
  28. ipNet, isValidIpNet := address.(*net.IPNet)
  29. if isValidIpNet && !ipNet.IP.IsLoopback() {
  30. if ipNet.IP.To4() != nil {
  31. ips = append(ips, ipNet.IP.String())
  32. }
  33. }
  34. }
  35. return ips
  36. }
  37. func main() {
  38. fmt.Printf("mac addrs: %q\n", getMacAddrs())
  39. fmt.Printf("ips: %q\n", getIPs())
  40. }