github.com/tickstep/library-go@v0.1.1/getip/getip.go (about)

     1  // Package getip 获取 ip 信息包
     2  package getip
     3  
     4  import (
     5  	"github.com/tickstep/library-go/requester"
     6  	"net"
     7  	"net/http"
     8  	"unsafe"
     9  )
    10  
    11  // IPInfoByClient 给定client获取ip地址
    12  func IPInfoByClient(c *requester.HTTPClient) (ipAddr string, err error) {
    13  	if c == nil {
    14  		c = requester.NewHTTPClient()
    15  	}
    16  
    17  	body, err := c.Fetch(http.MethodGet, "https://api.ipify.org", nil, nil)
    18  	if err != nil {
    19  		return
    20  	}
    21  
    22  	ipAddr = *(*string)(unsafe.Pointer(&body))
    23  	ip := net.ParseIP(ipAddr)
    24  	if ip == nil {
    25  		return "", ErrParseIP
    26  	}
    27  	return
    28  }
    29  
    30  //IPInfo 从ipify获取IP地址
    31  func IPInfo(https bool) (ipAddr string, err error) {
    32  	c := requester.NewHTTPClient()
    33  	c.SetHTTPSecure(https)
    34  	return IPInfoByClient(c)
    35  }