Golang 字符串ip地址与Long类型互转
将IP地址以字符串的形式存储在数据库是对数据库查询效率方面有些影响的,转成数字类型就能提高数据库查询效率,所以催生类IP地址与Long类型转换的需求:
package main
import (
"encoding/binary"
"fmt"
"net"
)
func main() {
fmt.Println(Ip2long("192.168.255.90"))
fmt.Println(Long2ip(3232300890))
}
func Ip2long(ipstr string) uint32 {
ip := net.ParseIP(ipstr)
if ip == nil {
return 0
}
ip = ip.To4()
return binary.BigEndian.Uint32(ip)
}
func Long2ip(ipLong uint32) string {
ipByte := make([]byte, 4)
binary.BigEndian.PutUint32(ipByte, ipLong)
ip := net.IP(ipByte)
return ip.String()
}