commit
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
package ipx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// TODO:不符合预期
|
||||
|
||||
// 获取本机的公网IP
|
||||
func GetPublicIP() string {
|
||||
|
||||
conn, err := net.Dial("udp", "114.114.114.114:53")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return ""
|
||||
}
|
||||
|
||||
defer conn.Close()
|
||||
|
||||
remoteAddr := conn.RemoteAddr().(*net.UDPAddr)
|
||||
fmt.Println("remote:", remoteAddr.String())
|
||||
localAddr := conn.LocalAddr().(*net.UDPAddr)
|
||||
fmt.Println("local:", localAddr.String())
|
||||
ip := strings.Split(localAddr.String(), ":")[0]
|
||||
return ip
|
||||
}
|
||||
|
||||
// 获取本机的内网IP
|
||||
func GetLocalIP() string {
|
||||
addrs, err := net.InterfaceAddrs()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return ""
|
||||
}
|
||||
fmt.Println(addrs)
|
||||
for _, address := range addrs {
|
||||
// 检查ip地址判断是否回环地址
|
||||
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
|
||||
if ipnet.IP.To4() != nil {
|
||||
ip := ipnet.IP.String()
|
||||
return ip
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
Reference in New Issue
Block a user