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

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

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

是否存在类似于“ npm网络掩码 ”的内容 高朗 我需要将10.0.0.0/ 8 转换为10.0.0.0/ 255.0.0.0 ,因此基本上将CIDR格式的网络掩码转换为点十进制。

  var Netmask = require('netmask')。Netmask 
var block =新的Netmask('10 .0.0.0 / 8'); 
block.mask;  // 255.0.0.0 
   
 
 

我在/golang.org/src/net/ip.go

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

1条回答 默认 最新

  • douliang1891
    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.

    点赞 评论

相关推荐