go IP地址的操作

随记一下,开发过程中,对于IP地址的操作

package ip

import (
	"fmt"
	"math/big"
	"net"
	"net/http"
	"regexp"
)

// 获取 ip 地址
func RemoteIp(req *http.Request) string {
	remoteAddr := req.Header.Get("Remote_addr")
	if remoteAddr == "" {
		if ip := req.Header.Get("ipv4"); ip != "" {
			remoteAddr = ip
		} else if ip = req.Header.Get("XForwardedFor"); ip != "" {
			remoteAddr = ip
		} else if ip = req.Header.Get("X-Forwarded-For"); ip != "" {
			remoteAddr = ip
		} else {
			remoteAddr = req.Header.Get("X-Real-Ip")
		}
	}

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

	return remoteAddr
}

// 校验ip地址
func JudgeIp(ip string) (ok bool) {
	return net.ParseIP(ip) != nil
}

// ip 转 10进制
func IpStringToInt(ip string) int64 {
	ret := big.NewInt(0)
	ret.SetBytes(net.ParseIP(ip).To4())
	return ret.Int64()
}

// 10进制 转 ip
func IpIntToString(ip int64) string {
	return fmt.Sprintf("%d.%d.%d.%d",
		byte(ip>>24), byte(ip>>16), byte(ip>>8), byte(ip))
}

// 输入地址是否在白名单中::ipList 是用 | 分隔的字符串
func HadExist(ipList string, ip string) (ok bool, err error) {
	ok, err = regexp.MatchString(ipList, ip)
	return
}


你可能感兴趣的:(go,基础知识,golang,ip)