network.go 543 B

123456789101112131415161718192021222324252627
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package util
  4. import (
  5. "errors"
  6. "net"
  7. )
  8. // LocalIP() 获取本机IP
  9. // 返回结果:IPv6 或 IPv4
  10. func LocalIP() (string, error) {
  11. addrs, err := net.InterfaceAddrs()
  12. if err != nil {
  13. return "", err
  14. }
  15. for _, addr := range addrs {
  16. if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  17. if ipnet.IP.To4() != nil {
  18. return ipnet.IP.String(), nil
  19. }
  20. }
  21. }
  22. return "", errors.New("get ip address failed.")
  23. }