Browse Source

wip:获取当前服务器ip信息

wangshan 1 year ago
parent
commit
6d8429bb4d
1 changed files with 36 additions and 3 deletions
  1. 36 3
      common/requtil.go

+ 36 - 3
common/requtil.go

@@ -2,12 +2,13 @@
 package common
 package common
 
 
 import (
 import (
+	"fmt"
 	"net"
 	"net"
 	"net/http"
 	"net/http"
 	"strings"
 	"strings"
 )
 )
 
 
-//获取平台类型
+// 获取平台类型
 func GetOS(useros string) string {
 func GetOS(useros string) string {
 	osVersion := "其他"
 	osVersion := "其他"
 	if strings.Contains(useros, "NT 6.0") {
 	if strings.Contains(useros, "NT 6.0") {
@@ -36,7 +37,7 @@ func GetOS(useros string) string {
 	return osVersion
 	return osVersion
 }
 }
 
 
-//获取浏览器类型
+// 获取浏览器类型
 func GetBrowse(userbrowser string) string {
 func GetBrowse(userbrowser string) string {
 	browserVersion := "其他"
 	browserVersion := "其他"
 	if strings.Contains(userbrowser, "MSIE") {
 	if strings.Contains(userbrowser, "MSIE") {
@@ -53,7 +54,7 @@ func GetBrowse(userbrowser string) string {
 	return browserVersion
 	return browserVersion
 }
 }
 
 
-//获取ip
+// 获取ip
 func GetIp(req *http.Request) string {
 func GetIp(req *http.Request) string {
 	if req == nil {
 	if req == nil {
 		return ""
 		return ""
@@ -74,3 +75,35 @@ func GetIp(req *http.Request) string {
 	ip, _, _ := net.SplitHostPort(req.RemoteAddr)
 	ip, _, _ := net.SplitHostPort(req.RemoteAddr)
 	return ip
 	return ip
 }
 }
+
+// 获取当前服务器ip
+func GetLocationIp() (ips []string) {
+	// 获取所有网络接口
+	interfaces, err := net.Interfaces()
+	if err != nil {
+		fmt.Println("获取网络接口错误:", err)
+		return
+	}
+	// 遍历网络接口,找到非回环接口的 IPv4 地址
+	for _, iface := range interfaces {
+		// 排除回环接口和无效接口
+		if iface.Flags&net.FlagLoopback == 0 && iface.Flags&net.FlagUp != 0 {
+			addresses, err := iface.Addrs()
+			if err != nil {
+				fmt.Println("获取接口地址错误:", err)
+				return
+			}
+
+			// 遍历接口地址,找到第一个 IPv4 地址
+			for _, addr := range addresses {
+				ipNet, ok := addr.(*net.IPNet)
+				if ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
+					ip := ipNet.IP
+					ips = append(ips, fmt.Sprint(ip))
+					fmt.Println("当前服务器环境的 IP 地址:", ip)
+				}
+			}
+		}
+	}
+	return
+}