2022-05-30 23:49:07

go语言ip相关的操作

记录go中一些常用的ip操作场景

1.IP地址转数字

func IPToInt(v string) *big.Int { ip := net.ParseIP(v).To4() if val := ip.To4(); val != nil { return big.NewInt(0).SetBytes(val) } return big.NewInt(0).SetBytes(ip.To16()) }

2.数字转IP地址

func IntToIP(v *big.Int) net.IP { return v.Bytes() }

3.解析IP段

解析10.0.0.1-10.0.0.12

func ParseIPs(ipList []string) (res []string) { for _, i := range ipList { if strings.Contains(i, "-") { if err := AssemblyIPList(&i); err != nil { fmt.Printf("failed to get Addrs, %s", err.Error()) continue } res = append(res, strings.Split(i, ",")...) } res = append(res, i) } return } func AssemblyIPList(args *string) error { var result string var ips = strings.Split(*args, "-") if *args == "" || !strings.Contains(*args, "-") { return nil } if len(ips) != 2 { return fmt.Errorf("ip is invalid,ip range format is xxx.xxx.xxx.1-xxx.xxx.xxx.2") } if !checkIP(ips[0]) || !checkIP(ips[1]) { return fmt.Errorf("ip is invalid,check you command agrs") } for res, _ := CompareIP(ips[0], ips[1]); res <= 0; { result = ips[0] + "," + result ips[0] = NextIP(ips[0]).String() res, _ = CompareIP(ips[0], ips[1]) } if result == "" { return fmt.Errorf("ip is invalid,check you command agrs") } *args = result return nil } func checkIP(ipStr string) bool { return net.ParseIP(ipStr) != nil } func CompareIP(v1, v2 string) (int, error) { i := IPToInt(v1) j := IPToInt(v2) if i == nil || j == nil { return 2, fmt.Errorf("ip is invalid,check you command agrs") } return i.Cmp(j), nil }

本文链接:https://troy.wang/post/go_ip.html

-- EOF --