ip4的地址格式為255.255.255.255,很顯然最大值255可以使用一個字節來保存,總共使用4個字節就可以保存,所以使用一個32位的int整型來保存ip地址。
之后從int整形轉為ip字符串時,分別對32位的每8位進行處理即可,均可以通過簡單的位運算獲得
廢話不多說直接上代碼
package iphelper import ( "strings" "strconv" "bytes" ) func StringIpToInt(ipstring string) int { ipSegs := strings.Split(ipstring, ".") var ipInt int = 0 var pos uint = 24 for _, ipSeg := range ipSegs { tempInt, _ := strconv.Atoi(ipSeg) tempInt = tempInt << pos ipInt = ipInt | tempInt pos -= 8 } return ipInt } func IpIntToString(ipInt int) string { ipSegs := make([]string, 4) var len int = len(ipSegs) buffer := bytes.NewBufferString("") for i := 0; i < len; i++ { tempInt := ipInt & 0xFF ipSegs[len-i-1] = strconv.Itoa(tempInt) ipInt = ipInt >> 8 } for i := 0; i < len; i++ { buffer.WriteString(ipSegs[i]) if i < len-1 { buffer.WriteString(".") } } return buffer.String() }