|
- package main
-
- import (
- "bytes"
- "encoding/binary"
- "net"
- "net/http"
- "strconv"
- "strings"
- )
-
- func ip2Long(ip string) uint32 {
- var long uint32
- binary.Read(bytes.NewBuffer(net.ParseIP(ip).To4()), binary.BigEndian, &long)
- return long
- }
-
- func backtoIP4(ipInt int64) string {
-
- // need to do two bit shifting and “0xff” masking
- b0 := strconv.FormatInt((ipInt>>24)&0xff, 10)
- b1 := strconv.FormatInt((ipInt>>16)&0xff, 10)
- b2 := strconv.FormatInt((ipInt>>8)&0xff, 10)
- b3 := strconv.FormatInt((ipInt & 0xff), 10)
- return b0 + "." + b1 + "." + b2 + "." + b3
- }
-
- func getClientIP(r *http.Request) string {
- a := r.RemoteAddr // always be 127.0.0.1:300456 port number may vary
- s := strings.Split(a, ":")
- if s[0] == "127.0.0.1" { //loopback address
- ip := r.Header.Get("X-Forwarded-For")
- return ip
- }
- return s[0]
- }
-
- func getClientIPLong(r *http.Request) uint32 {
- s := getClientIP(r)
- return ip2Long(s)
- }
|