github.com/wfusion/gofusion@v1.1.14/common/utils/ip.go (about)

     1  package utils
     2  
     3  import (
     4  	"net"
     5  )
     6  
     7  func ClientIP() (ip string) {
     8  	addrs, err := net.InterfaceAddrs()
     9  	if err != nil {
    10  		panic(err)
    11  	}
    12  
    13  	for _, address := range addrs {
    14  		if addr, ok := address.(*net.IPNet); ok && !addr.IP.IsLoopback() {
    15  			if addr.IP.To4() != nil {
    16  				return addr.IP.String()
    17  			}
    18  
    19  		}
    20  	}
    21  
    22  	return
    23  }
    24  
    25  func HostIPInDocker() (ip string) {
    26  	addrs, err := net.LookupIP("host.docker.internal")
    27  	if err != nil {
    28  		return
    29  	}
    30  
    31  	for _, addr := range addrs {
    32  		if addr.To4() != nil {
    33  			return addr.String()
    34  		}
    35  	}
    36  	return
    37  }
    38  
    39  type localIP struct {
    40  	_     func()
    41  	bytes []byte
    42  	str   string
    43  }
    44  
    45  func (l *localIP) Bytes() (d []byte) {
    46  	if l.bytes == nil {
    47  		return
    48  	}
    49  	d = make([]byte, len(l.bytes), cap(l.bytes))
    50  	copy(d, l.bytes)
    51  	return
    52  }
    53  
    54  func (l *localIP) String() string {
    55  	return l.str
    56  }
    57  
    58  var LocalIP = &localIP{
    59  	str: ClientIP(),
    60  	bytes: func() []byte {
    61  		reverse := func(bs []byte) {
    62  			i, j := 0, len(bs)-1
    63  			for i < j {
    64  				bs[i], bs[j] = bs[j], bs[i]
    65  				i++
    66  				j--
    67  			}
    68  		}
    69  
    70  		if ipAddr := ClientIP(); ipAddr != "" {
    71  			realIP := []byte("000000000000")
    72  			idx := 0
    73  			for i := len(ipAddr) - 1; i >= 0; i-- {
    74  				c := ipAddr[i]
    75  				if c == '.' {
    76  					idx = (((idx - 1) / 3) + 1) * 3
    77  					continue
    78  				}
    79  				realIP[idx] = c
    80  				idx++
    81  			}
    82  			reverse(realIP)
    83  			return realIP
    84  		}
    85  		return []byte("000000000000")
    86  	}(),
    87  }