douyiyang6317 2017-09-05 20:55
浏览 1064
已采纳

IP地址/子网掩码的golang CIDR前缀表示法(点十进制)

Is there something similar to 'npm netmask' in golang ? I need to convert i.e. 10.0.0.0/8 to 10.0.0.0/255.0.0.0 so basically netmask in CIDR format to dot-decimal.

var Netmask = require('netmask').Netmask
var block = new Netmask('10.0.0.0/8');
block.mask; // 255.0.0.0

I can't find it in /golang.org/src/net/ip.go

  • 写回答

1条回答 默认 最新

  • douliang1891 2017-09-05 21:07
    关注

    The go standard library does not have a function to create that representation. That being said, it is not difficult to do yourself:

    https://play.golang.org/p/XT_UXoy6ra

    func main() {
        _, ipv4Net, err := net.ParseCIDR("10.0.0.0/8")
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(ipv4MaskString(ipv4Net.Mask))
    }
    
    func ipv4MaskString(m []byte) string {
        if len(m) != 4 {
            panic("ipv4Mask: len must be 4 bytes")
        }
    
        return fmt.Sprintf("%d.%d.%d.%d", m[0], m[1], m[2], m[3])
    }
    

    Keep in mind this format only works for ipv4 masks. If you were to pass an ipv6 mask, this would panic.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装opengauss数据库报错
  • ¥15 【急】在线问答CNC雕刻机的电子电路与编程
  • ¥60 在mc68335芯片上移植ucos ii 的成功工程文件
  • ¥15 笔记本外接显示器正常,但是笔记本屏幕黑屏
  • ¥15 Python pandas
  • ¥15 蓝牙硬件,可以用哪几种方法控制手机点击和滑动
  • ¥15 生物医学数据分析。基础课程就v经常唱课程舅成牛逼
  • ¥15 云环境云开发云函数对接微信商户中的分账功能
  • ¥15 空间转录组CRAD遇到问题
  • ¥20 materialstudio计算氢键脚本问题