dongliyan9190 2019-08-28 20:37
浏览 260
已采纳

在Go中将网络掩码转换为CIDR

I'm looking for a way to convert a netmask string into CIDR notation in Go.

For instance, "255.255.255.0" -> "/24"

I'm currently obtaining an IP address and the net mask string with the below logic, which may just be complicating things.

I've been perusing the net library trying to see if there is a different function to use to accomplish what I'd like, which is really just a IP address in CIDR notation:

192.168.1.2/24
var mgmtInterface *net.Interface
var err error

mgmtInterface, err = net.InterfaceByName("eth0")
if err != nil {
  log.Println("Unable to find interface eth0, trying en0")
  mgmtInterface, err = net.InterfaceByName("en0")
}

addrs, err := mgmtInterface.Addrs()
if err != nil {
  log.Println("interface has no address")
}

for _, addr := range addrs {
  var ip net.IP
  var mask net.IPMask
  switch v := addr.(type) {
  case *net.IPNet:
    ip = v.IP
    mask = v.Mask
  case *net.IPAddr:
    ip = v.IP
    mask = ip.DefaultMask()
  }

  if ip == nil {
    continue
  }

  ip = ip.To4()
  if ip == nil {
    continue
  }

  // create the netmask
  cleanMask := fmt.Sprintf("%d.%d.%d.%d", mask[0], mask[1], mask[2], mask[3])

} 
  • 写回答

2条回答 默认 最新

  • douguangxiang0363 2019-08-28 22:53
    关注

    This isn't very obvious at first, but:

    addr := ip.To4()
    sz, _ := net.IPV4Mask(addr[0], addr[1], addr[2], addr[3]).Size()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • duanbinian2243 2019-08-28 23:12
    关注

    I'm not aware about existense of such function but it's easy to create one.

    CIDR notation is just a count of set bits in netmask.

    So, crude solution could be:

    func cidr(netmask string) int {       
            var mask uint32
        for idx, dotpart := range strings.Split(netmask, ".") {
            part, _ := strconv.Atoi(dotpart)    
            mask = mask | uint32(part) << uint32(24-idx*8)
        }   
        return len(fmt.Sprintf("%b", mask))
    }
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#tensorflow#的问题:有没有什么方法可以让机器自己学会像素风格的图片
  • ¥15 Oracle触发器字段变化时插入指定值
  • ¥15 docker无法进入容器内部
  • ¥15 qt https 依赖openssl 静态库
  • ¥15 python flask 报错
  • ¥15 改个密码引发的项目启动问题
  • ¥100 CentOS7单线多拨
  • ¥15 debian安装过程中老是出现无法将g21dr复制到g21dr怎么解决呀?
  • ¥15 如何用python实现跨工作簿的指定区域批量复制粘贴
  • ¥15 基于CH573f的雷迪安CR1400m通讯代码