3 回答
TA贡献1777条经验 获得超10个赞
func main() {
ifaces, err := net.Interfaces()
if err != nil {
panic(err)
}
for _, iface := range ifaces {
addrs, _ := iface.Addrs()
for _, addr := range addrs {
cidr := addr.String()
mask, err := mask(cidr)
if err != nil {
fmt.Println("extracting mask failed:", err)
}
i, err := mtoi(mask)
if err != nil {
fmt.Println("creating uint16 from mask failed:", err)
}
fmt.Printf("CIDR: %s\tMask: %d\n", cidr, i)
}
}
}
// Extracts IP mask from CIDR address.
func mask(cidr string) (net.IPMask, error) {
_, ip, err := net.ParseCIDR(cidr)
return ip.Mask, err
}
// Converts IP mask to 16 bit unsigned integer.
func mtoi(mask net.IPMask) (uint16, error) {
var i uint16
buf := bytes.NewReader(mask)
err := binary.Read(buf, binary.BigEndian, &i)
return i, err
}
TA贡献1853条经验 获得超18个赞
借用一些 stackoverflow 帖子本身,使用逻辑运算符。
mask = (0xFFFFFFFF << (32 - 24)) & 0xFFFFFFFF; //24 is the netmask
var dmask uint64
dmask = 32
localmask := make([]uint64, 0, 4)
for i := 1; i <= 4; i++{
tmp := mask >> (dmask - 8) & 0xFF
localmask = append(localmask, tmp)
dmask -= 8
}
fmt.Println(localmask)
TA贡献1891条经验 获得超3个赞
您可以实现如下功能:
func parseMask(ipaddr string) (mask string, err error) {
removeExtra := regexp.MustCompile("^(.*[\\/])")
asd := ipaddr[len(ipaddr)-3:]
findSubnet := removeExtra.ReplaceAll([]byte(asd), []byte(""))
subnet, err := strconv.ParseInt(string(findSubnet), 10, 64)
if err != nil {
return "", errors.New("Parse Mask: Error parsing mask")
}
var buff bytes.Buffer
for i := 0; i < int(subnet); i++ {
buff.WriteString("1")
}
for i := subnet; i < 32; i++ {
buff.WriteString("0")
}
masker := buff.String()
a, _ := strconv.ParseUint(masker[:8], 2, 64)
b, _ := strconv.ParseUint(masker[8:16], 2, 64)
c, _ := strconv.ParseUint(masker[16:24], 2, 64)
d, _ := strconv.ParseUint(masker[24:32], 2, 64)
resultMask := fmt.Sprintf("%v.%v.%v.%v", a, b, c, d)
return resultMask, nil
}
然后调用它:
func main() {
ifaces, _ := net.Interfaces()
for _, iface := range ifaces {
localip, _ := iface.Addrs()
for _, ip := range localip {
done, _ := parseMask(ip.String())
log.Println(done) // 255.255.255.0
}
}
}
- 3 回答
- 0 关注
- 357 浏览
添加回答
举报