GoLang get the Client’s real IP.

🤡 注意import指定的包或者庫。

 

😀 一些Golang常用的快捷函數,想要寫花費一番時間,既然在PHP的編程中已經經歷了一遍,那麼就稍微總結一下

 

Golang 獲取客戶端真實IP

//來自github,原理大概和PHP相同
func RemoteIP(req *http.Request) string {
    remoteAddr := req.RemoteAddr
    if ip := req.Header.Get("X-Real-IP"); ip != "" {
        remoteAddr = ip
    } else if ip = req.Header.Get("X-Forwarded-For"); ip != "" {
        remoteAddr = ip
    } else {
        remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
    }

    if remoteAddr == "::1" {
        remoteAddr = "127.0.0.1"
    }
    return remoteAddr
}

當初決定接觸Golang的原因是想了解一些Golang的編程方式,發現也有指針,就寫了一個Web的應用程式。

Ip2long 将 IPv4 字符串形式转为 uint32

// 
func Ip2long(ipstr string) uint32 {
    ip := net.ParseIP(ipstr)
    if ip == nil {
        return 0
    }
    ip = ip.To4()
    return binary.BigEndian.Uint32(ip)
}

Leave a Reply

Your email address will not be published. Required fields are marked *