
php editor Banana will introduce you how to use Golang to list subnets in the network. Golang is a powerful programming language that provides many features and libraries to easily handle network-related tasks. To list subnets in a network, we can use Golang’s net package and CIDR (Classless Inter-Domain Routing) library. By parsing the IP address and subnet mask, we can calculate all the subnets in the network. Next, we will explain in detail how to use Golang to write code to implement this function.
Question content
I want to list it. subnet in network, I have sample working code in python but need it in golang.
NETWORK="192.168.0.0/16"
subnet_prefix=22
net = ipaddress.ip_network(NETWORK)
for subnet in net.subnets(new_prefix=subnet_prefix):
net = ipaddress.ip_interface(subnet)
print(net)
192.168.0.0/22 192.168.4.0/22 192.168.8.0/22 192.168.12.0/22 192.168.16.0/22 192.168.20.0/22 192.168.24.0/22 192.168 . 28.0/22 192.168.32.0/ 22 192.168.36.0/22 192.168.40.0/22 192.168.44.0/22 192.168.48.0/22 192.168.52.0/22 192.168.56.0/22 192.168.60.0/22 192.168. 64. 0/22 192.168.68.0/22 192.168.72.0/22 192.168.76.0/22 192.168.80.0/22 192.168.84.0/22 192.168.88.0/22 192.168.92.0/22 192.16 8.96.0/22 192.168.100.0/22 192.168. 10 4.0/22 192.168.108.0/22 192.168.112.0/22 192.168.116.0/22 192.168.120.0/22 192.168.124.0/22 192.168.128.0/22 192.168.132 .0/22 192.168.136.0/22 192.168.140.0/22 192 . 168.144.0/22 192.168.148.0/22 192.168.152.0/22 192.168.156.0/22 192.168.160.0/22 192.168.164.0/22 192.168.168.0/22 192.168. 172.0/22 192.168.176.0/22 192.168.180.0/22 192. 168.184.0/22 192.168.188.0/22 192.168.192.0/22 192.168.196.0/22 192.168.200.0/22 192.168.204.0/22 192.168.208.0/22 192.168. 212.0/22 192.168.216.0/22 192.168.220.0/22 192. 168.224.0/22 192.168.228.0/22 192.168.232.0/22 192.168.236.0/22 192.168.240.0/22 192.168.244.0/22 192.168.248.0/22 192 .168.252.0/22
Solution
The function I wrote generates all subnets that can be created within a given netcidr given a subnetmasksize. Networks and subnets are represented in cidr notation.
For example:
func runner() {
fmt.println(gensubnetsinnetwork("192.168.0.0/24", 26))
}
=== run testrunner/run_me [192.168.0.0/26 192.168.0.64/26 192.168.0.128/26 192.168.0.192/26] <nil> --- pass: testrunner (0.00s)
I chose arithmetic operations so it's easier to understand (for better performance, use bitwise operations).
This function computes some facts about a given network and subnet mask, then generates all subnet cidrs.
func GenSubnetsInNetwork(netCIDR string, subnetMaskSize int) ([]string, error) {
ip, ipNet, err := net.ParseCIDR(netCIDR)
if err != nil {
return nil, err
}
if !ip.Equal(ipNet.IP) {
return nil, errors.New("netCIDR is not a valid network address")
}
netMaskSize, _ := ipNet.Mask.Size()
if netMaskSize > int(subnetMaskSize) {
return nil, errors.New("subnetMaskSize must be greater or equal than netMaskSize")
}
totalSubnetsInNetwork := math.Pow(2, float64(subnetMaskSize)-float64(netMaskSize))
totalHostsInSubnet := math.Pow(2, 32-float64(subnetMaskSize))
subnetIntAddresses := make([]uint32, int(totalSubnetsInNetwork))
// first subnet address is same as the network address
subnetIntAddresses[0] = ip2int(ip.To4())
for i := 1; i < int(totalSubnetsInNetwork); i++ {
subnetIntAddresses[i] = subnetIntAddresses[i-1] + uint32(totalHostsInSubnet)
}
subnetCIDRs := make([]string, 0)
for _, sia := range subnetIntAddresses {
subnetCIDRs = append(
subnetCIDRs,
int2ip(sia).String()+"/"+strconv.Itoa(int(subnetMaskSize)),
)
}
return subnetCIDRs, nil
}
func ip2int(ip net.IP) uint32 {
if len(ip) == 16 {
panic("cannot convert IPv6 into uint32")
}
return binary.BigEndian.Uint32(ip)
}
func int2ip(nn uint32) net.IP {
ip := make(net.IP, 4)
binary.BigEndian.PutUint32(ip, nn)
return ip
}
The above is the detailed content of How to list subnets in a network using golang?. For more information, please follow other related articles on the PHP Chinese website!
Golang vs. C : Code Examples and Performance AnalysisApr 15, 2025 am 12:03 AMGolang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.
Golang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AMGoimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:
C and Golang: When Performance is CrucialApr 13, 2025 am 12:11 AMC is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.
Golang in Action: Real-World Examples and ApplicationsApr 12, 2025 am 12:11 AMGolang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.
Golang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AMThe core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.
Golang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PMGo language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.
Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PMConfused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...
Is technology stack convergence just a process of technology stack selection?Apr 02, 2025 pm 05:21 PMThe relationship between technology stack convergence and technology selection In software development, the selection and management of technology stacks are a very critical issue. Recently, some readers have proposed...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software







