1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- package geodb
- import (
- "net"
- "net/http"
- "strings"
- )
- func GetRequesterIP(r *http.Request) string {
- ip := r.Header.Get("X-Forwarded-For")
- if ip == "" {
- ip = r.Header.Get("X-Real-IP")
- if ip == "" {
- ip = strings.Split(r.RemoteAddr, ":")[0]
- }
- }
- return ip
- }
- func MatchIpWildcard(ipAddress, wildcard string) bool {
-
- ipOctets := strings.Split(ipAddress, ".")
- wildcardOctets := strings.Split(wildcard, ".")
-
- if len(ipOctets) != 4 || len(wildcardOctets) != 4 {
- return false
- }
-
- for i := 0; i < 4; i++ {
- if wildcardOctets[i] == "*" {
- continue
- }
- if ipOctets[i] != wildcardOctets[i] {
- return false
- }
- }
- return true
- }
- func MatchIpCIDR(ip string, cidr string) bool {
-
- _, cidrnet, err := net.ParseCIDR(cidr)
- if err != nil {
- return false
- }
-
- ipAddr := net.ParseIP(ip)
-
- return cidrnet.Contains(ipAddr)
- }
- func IsPrivateIP(ipStr string) bool {
- ip := net.ParseIP(ipStr)
- if ip == nil {
- return false
- }
-
- if ip.To4() != nil {
- privateIPv4Ranges := []string{
- "10.0.0.0/8",
- "172.16.0.0/12",
- "192.168.0.0/16",
- "169.254.0.0/16",
- }
- for _, network := range privateIPv4Ranges {
- _, privateNet, _ := net.ParseCIDR(network)
- if privateNet.Contains(ip) {
- return true
- }
- }
- } else {
-
- privateIPv6Ranges := []string{
- "fc00::/7",
- "fe80::/10",
- }
- for _, network := range privateIPv6Ranges {
- _, privateNet, _ := net.ParseCIDR(network)
- if privateNet.Contains(ip) {
- return true
- }
- }
- }
- return false
- }
|