Golang(Go语言)IP地址转换函数

发布时间 2023-11-01 00:59:11作者: 烟熏牛肉干

String形式的IP地址和Int类型互转函数

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "strconv"
 6     "strings"
 7 )
 8 
 9 func main() {
10     ip1 := `172.16.1.2`
11     ipInt1 := 2886729986
12     fmt.Printf("%s转换为int类型:%d\n", ip1, *ip2int(&ip1))
13     fmt.Printf("%d转换为string类型:%s\n", ipInt1, *int2ip(&ipInt1))
14 }
15 
16 func ip2int(ip *string) *int {
17     ipSegs := strings.Split(*ip, ".")
18     result := 0
19     for i, v := range ipSegs {
20         seg, _ := strconv.Atoi(v)
21         seg <<= (3 - i) * 8
22         result |= seg
23     }
24     return &result
25 }
26 
27 func int2ip(ipInt *int) *string {
28     var ipSegs []string
29     for i := 0; i < 4; i++ {
30         ipSegs = append(ipSegs, strconv.Itoa(*ipInt>>((3-i)*8)&255))
31     }
32     result := strings.Join(ipSegs, ".")
33     return &result
34 }
代码

输出如下: