From cb2fdf2ffd3df82b3e3c8727310a03f2496a1da7 Mon Sep 17 00:00:00 2001 From: wangsiyuan <2392948297@qq.com> Date: Fri, 16 Jun 2023 16:07:00 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=9B=E5=BB=BA=20CheckBelongPrivate.go?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/CheckBelongPrivate.go | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 modules/CheckBelongPrivate.go diff --git a/modules/CheckBelongPrivate.go b/modules/CheckBelongPrivate.go new file mode 100644 index 0000000..7187e7e --- /dev/null +++ b/modules/CheckBelongPrivate.go @@ -0,0 +1,50 @@ +package modules + +import ( + "fmt" + "net" +) + +type IPInformation struct { + IP string + IsPrivate bool + PrivateCIDR string +} + +func GetIPInformation(ip string) IPInformation { + ipInfo := IPInformation{ + IP: ip, + IsPrivate: false, + PrivateCIDR: "", + } + + cidrs := []*net.IPNet{ + parseCIDR("10.0.0.0/8"), + parseCIDR("172.16.0.0/12"), + parseCIDR("192.168.0.0/16"), + } + + ipAddr := net.ParseIP(ip) + if ipAddr == nil { + fmt.Println("无效的IP地址") + return ipInfo + } + + for _, cidr := range cidrs { + if cidr.Contains(ipAddr) { + ipInfo.IsPrivate = true + ipInfo.PrivateCIDR = cidr.String() + break + } + } + + return ipInfo +} + +func parseCIDR(cidr string) *net.IPNet { + _, ipNet, err := net.ParseCIDR(cidr) + if err != nil { + panic(err) + } + return ipNet +}