123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125 |
- package netutils
- import (
- "net"
- "net/http"
- "strings"
- )
- func GetRequesterIP(r *http.Request) string {
- ip := r.Header.Get("X-Real-Ip")
- if ip == "" {
- ip = r.Header.Get("X-Forwarded-For")
- }
- if ip == "" {
- ip = r.RemoteAddr
- }
-
- requesterRawIp := ip
- if strings.Contains(requesterRawIp, ",") {
-
- requesterRawIp = strings.Split(requesterRawIp, ",")[0]
- }
-
- reqHost, _, err := net.SplitHostPort(requesterRawIp)
- if err == nil {
- requesterRawIp = reqHost
- }
- if strings.HasPrefix(requesterRawIp, "[") && strings.HasSuffix(requesterRawIp, "]") {
-
- requesterRawIp = requesterRawIp[1 : len(requesterRawIp)-1]
- }
- return requesterRawIp
- }
- 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 {
- if ipStr == "127.0.0.1" || ipStr == "::1" {
-
- return true
- }
- ip := net.ParseIP(ipStr)
- if ip == nil {
- return false
- }
- return ip.IsPrivate()
- }
- func IsIPv6(ipStr string) bool {
- ip := net.ParseIP(ipStr)
- if ip == nil {
- return false
- }
- return ip.To4() == nil && ip.To16() != nil
- }
- func IsIPv4(ipStr string) bool {
- ip := net.ParseIP(ipStr)
- if ip == nil {
- return false
- }
- return ip.To4() != nil
- }
|