doushangan3690
2014-06-11 17:34
浏览 1.0k
已采纳

golang将字符串转换为net.IPNet类型

I have a slice of strings that are in CIDR notation. They are both ipv4 and ipv6 and I need them cast into the type net.IPNet.

How would I do this in golang?

example strings:

192.168.1.1/24
fd04:3e42:4a4e:3381::/64

图片转代码服务由CSDN问答提供 功能建议

我有一片使用CIDR表示法的字符串。 它们都是ipv4和ipv6,我需要将它们强制转换为net.IPNet类型。

我该如何在golang中做到这一点?

示例字符串:

192.168.1.1/24
fd04:3e42:4a4e:3381 :: / 64 \ n

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • donglu8549 2014-06-11 17:43
    已采纳

    As cnicutar says use net.ParseCIDR.

    This is a working example on how to actually use it.

    http://play.golang.org/p/Wtqy56LS2Y

    package main
    
    import (
        "fmt"
        "net"
    )
    
    func main() {
        ipList := []string{"192.168.1.1/24", "fd04:3e42:4a4e:3381::/64"}
        for i := 0; i < len(ipList); i += 1 {
            ip, ipnet, err := net.ParseCIDR(ipList[i])
            if err != nil {
                fmt.Println("Error", ipList[i], err)
                continue
            }
            fmt.Println(ipList[i], "-> ip:", ip, " net:", ipnet)
        }
    }
    
    已采纳该答案
    打赏 评论
  • dongshaoxiong0012 2014-06-11 17:37

    I don't think you want casting; instead I think you want ParseCIDR

    func ParseCIDR(s string) (IP, *IPNet, error)
    
    打赏 评论

相关推荐 更多相似问题