现在有这样的需求

正文

使用net包

net包的方法可以判断是否是 ip,需要注意的是 ip 分为 ipv4 和 ipv6
此方法将 v4 和 v6 一起判断出来

		address := net.ParseIP(ip)
		if address == nil {
			// 没有匹配上
			fmt.Println(ip)
		} else {
			// 匹配上
			fmt.Println(address)
		}

弊端: 无法获取到是 ipv4 还是 ipv6, 因此如果需求是去除 ipv6 需要自己写

匹配 ipv4

我们可以使用正则来匹配 ipv4

		matched, err := regexp.MatchString("((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}", ip)
		if err != nil {
			fmt.Println("ip匹配出现错误")
			return
		}
		if matched { // 匹配上了
			data = append(data, ip)
		}

相关文章:

  • 2022-12-23
  • 2021-08-17
  • 2022-12-23
  • 2021-09-04
  • 2022-12-23
  • 2021-12-26
  • 2021-12-26
  • 2021-12-26
猜你喜欢
  • 2021-10-01
  • 2022-12-23
  • 2021-12-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案