dragon7713 2014-01-07 12:41
浏览 202
已采纳

Golang:IP掩码的位数

In Go, how do I get the number of bits of an IP mask like this: 10.100.20.0 255.255.255.0 => 24 bits maks.

It would be helpful to check if a mask is lower or greater than a certain number of bits (like if one wants to block all adresses greater than /24).

  • 写回答

1条回答 默认 最新

  • douhu2890 2014-01-07 13:17
    关注

    The net package has functions for getting the prefix size of a mask, the value used in CIDR notation. The specific function for the bits is:

    func (m IPMask) Size() (ones, bits int)

    To get the bits, see the following example:

    package main
    
    import (
        "fmt"
        "net"
    )
    
    func main() {
        mask := net.IPMask(net.ParseIP("255.255.255.0").To4()) // If you have the mask as a string
        //mask := net.IPv4Mask(255,255,255,0) // If you have the mask as 4 integer values
    
        prefixSize, _ := mask.Size()
        fmt.Println(prefixSize)
    }
    

    Output:

    24

    Playground

    Ps.

    I assume you mean the bitmask 255.255.255.0

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

报告相同问题?

悬赏问题

  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输