github.com/wormhole-foundation/wormhole-explorer/common@v0.0.0-20240604151348-09585b5b97c5/utils/ip.go (about)

     1  package utils
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  
     7  	"github.com/gofiber/fiber/v2"
     8  )
     9  
    10  var privateIPBlocks []*net.IPNet
    11  
    12  func init() {
    13  	for _, cidr := range []string{
    14  		"127.0.0.0/8",    // IPv4 loopback
    15  		"10.0.0.0/8",     // RFC1918
    16  		"172.16.0.0/12",  // RFC1918
    17  		"192.168.0.0/16", // RFC1918
    18  		"169.254.0.0/16", // RFC3927 link-local
    19  		"::1/128",        // IPv6 loopback
    20  		"fe80::/10",      // IPv6 link-local
    21  		"fc00::/7",       // IPv6 unique local addr
    22  	} {
    23  		_, block, err := net.ParseCIDR(cidr)
    24  		if err != nil {
    25  			panic(fmt.Errorf("parse error on %q: %v", cidr, err))
    26  		}
    27  		privateIPBlocks = append(privateIPBlocks, block)
    28  	}
    29  }
    30  
    31  func IsPrivateIPAsString(ip string) bool {
    32  	ipAddress := net.ParseIP(ip)
    33  	return IsPrivateIP(ipAddress)
    34  }
    35  
    36  func IsPrivateIP(ip net.IP) bool {
    37  	if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
    38  		return true
    39  	}
    40  
    41  	for _, block := range privateIPBlocks {
    42  		if block.Contains(ip) {
    43  			return true
    44  		}
    45  	}
    46  	return false
    47  }
    48  
    49  func GetRealIp(c *fiber.Ctx) string {
    50  	ip := c.Get("x-forwarded-for")
    51  	if ip == "" {
    52  		ip = c.IP()
    53  	}
    54  	return ip
    55  }