IP to Decimal Converter – Convert IP to Integer
golang实现IP地址int与string类型互转的能力
IP to Integer
Integer to IP
package main
import (
"fmt"
"strconv"
"strings"
)
func ipToInt(ipStr string) uint32 {
numList := strings.Split(ipStr, ".")
ip1, _ := strconv.Atoi(numList[0])
ip2, _ := strconv.Atoi(numList[1])
ip3, _ := strconv.Atoi(numList[2])
ip4, _ := strconv.Atoi(numList[3])
return uint32(ip1&0xffff<<24 | ip2&0xffff<<16 | ip3&0xffff<<8 | ip4&0xffff)
}
func intToIP(ip uint32) string {
ip1 := ip >> 24 & 0xffff
ip2 := ip << 8 >> 24 & 0xffff
ip3 := ip << 16 >> 24 & 0xffff
ip4 := ip << 24 >> 24 & 0xffff
return fmt.Sprintf("%d.%d.%d.%d", ip1, ip2, ip3, ip4)
}
func main() {
ipStr := "10.100.67.132"
ip := ipToInt(ipStr)
fmt.Printf("string:%s | int:%d \n", ipStr, ip)
fmt.Printf("string:%s \n", intToIP(ip))
}
输出结果:
string:10.100.67.132 | int:174343044
string:10.100.67.132