代码拉取完成,页面将自动刷新
package system
import (
"io"
"net"
"net/http"
)
var (
ResolveIp = net.IP{}
PublicIp = net.IP{}
)
const (
KLocalHost = "127.0.0.1"
url = "https://myexternalip.com/raw"
)
func init() {
ResolveIp, _ = GetResolveIP()
PublicIp, _ = GetPublicIP()
}
func GetPublicIP() (net.IP, error) {
return GetPublicIPWithUrl(url)
}
func GetPublicIPWithUrl(url string) (net.IP, error) {
resp, err := http.Get(url)
if err != nil {
return net.IP{}, err
}
defer resp.Body.Close()
ip, err := io.ReadAll(resp.Body)
if err != nil {
return net.IP{}, err
}
return net.ParseIP(string(ip)), nil
}
func PublicIPValid() bool {
return len(PublicIp) > 0
}
// SelfExternalIP 自己外部IP,可能是局域网IP,公网IP
// lan 局域网优先
func SelfExternalIP(lan bool) string {
if lan && IsLanIP(ResolveIp) {
return ResolveIp.String()
}
if IsPublicIP(PublicIp) {
return PublicIp.String()
}
return ResolveIp.String()
}
// IPIsSelf 是否是自己
func IPIsSelf(ip string) string {
if PublicIp.String() == ip {
return KLocalHost
}
if ResolveIp.String() == ip {
return KLocalHost
}
return ip
}
// IsLanIP 是否局域网 192.168.x.x
func IsLanIP(IP net.IP) bool {
return GetIPType(IP) == IptPriC
}
func IsPublicIP(IP net.IP) bool {
return GetIPType(IP) == IptPub
}
func GetResolveIP() (net.IP, error) {
adds, err := net.InterfaceAddrs()
if err != nil {
return net.IP{}, err
}
return parseAddress(adds), nil
}
func GetResolveIPV2() (net.IP, error) {
faces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, face := range faces {
if face.Flags&net.FlagUp == 0 {
continue
}
if face.Flags&net.FlagLoopback != 0 {
continue
}
adds, er := face.Addrs()
if er != nil {
return nil, er
}
return parseAddress(adds), nil
}
return nil, err
}
func parseAddress(adds []net.Addr) net.IP {
for _, addr := range adds {
ip := parseResolveIP(addr)
if len(ip) > 0 {
return ip
}
}
return net.IP{}
}
func parseResolveIP(addr net.Addr) net.IP {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip == nil || ip.IsLoopback() {
return nil
}
ip = ip.To4()
if ip == nil {
return nil // not an ipv4 address
}
return ip
}
type IPType int8
const (
IptUnk = IPType(0)
IptPub = IPType(1)
IptPriA = IPType(2)
IptPriB = IPType(3)
IptPriC = IPType(4)
)
func GetIPType(IP net.IP) IPType {
if IP.IsLoopback() || IP.IsLinkLocalMulticast() || IP.IsLinkLocalUnicast() {
return IptPub
}
if ip4 := IP.To4(); ip4 != nil {
switch true {
case ip4[0] == 10:
return IptPriA
case ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31:
return IptPriB
case ip4[0] == 192 && ip4[1] == 168:
return IptPriC
default:
return IptPub
}
}
return IptUnk
}
/**
* 私有IP
A 类 10.0.0.0/8:10.0.0.0~10.255.255.255
B 类 172.16.0.0/12:172.16.0.0~172.31.255.255
C 192.168.0.0/16:192.168.0.0~192.168.255.255
*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。