go - 如何列出网络中的所有 IP

标签 go cidr

Python 在 ipaddress 中有一个方法模块列出网络中的所有 IP。例如。

import ipaddress
ips = [ip for ip in ipaddress.ip_network('8.8.8.0/24').hosts()]

你会如何在 Go 中做同样的事情?

最佳答案

将 CIDR 地址和网络掩码转换为 uint32。找到开始和结束,然后在 uint32 上循环以获取地址

package main

import (
    "encoding/binary"
    "fmt"
    "log"
    "net"
)

func main() {
    // convert string to IPNet struct
    _, ipv4Net, err := net.ParseCIDR("192.168.255.128/25")
    if err != nil {
        log.Fatal(err)
    }

    // convert IPNet struct mask and address to uint32
    // network is BigEndian
    mask := binary.BigEndian.Uint32(ipv4Net.Mask)
    start := binary.BigEndian.Uint32(ipv4Net.IP)

    // find the final address
    finish := (start & mask) | (mask ^ 0xffffffff)

    // loop through addresses as uint32
    for i := start; i <= finish; i++ {
         // convert back to net.IP
        ip := make(net.IP, 4)
        binary.BigEndian.PutUint32(ip, i)
        fmt.Println(ip)
    }

}

https://play.golang.org/p/5Yq0kXNnjYx

关于go - 如何列出网络中的所有 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60540465/

相关文章:

go - 如何一次迭代4个 slice

go - golang 中的 EnumChildWindows 回调函数

Golang TLS 握手错误 - "first record does not look like a TLS handshake"?

转到 ~(波浪字符)目录路径

networking - 如何计算 IP 范围

mysql - 有没有办法直接从 SELECT 查询中将 IP 与 IP+CIDR​​ 匹配?

java - Apache SubnetInfo 用于环回地址

go - 在 Kubernetes/Google Container Engine (GKE) 上使用 Stackdriver API 进行日志记录

go - net.IPNet 在其他 net.IPNet 里面?

algorithm - 如何对 trie 表中的 IP 地址进行排序?