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

在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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格