Generate Random IP Addresses in Go
Complete code tutorial with examples and best practices
[ Code Example - Quick Summary ]
Language: Go
What: Generate random IPv4 and IPv6 addresses in Go using math/rand and net.IP. Includes validation, RFC 1918 private ranges, and network testing utilities.
Try it: Use our interactive Ip-addresses generator or integrate this code into your Go application.
Generate random IPv4 and IPv6 addresses in Go using math/rand and net.IP. Includes validation, RFC 1918 private ranges, and network testing utilities. Looking for other languages? Check our code examples in PHP , JavaScript , Python , Java , C# , C++ and Ruby or use our interactive web generator.
Go Code Example
package main
import (
"fmt"
"math/rand"
"net"
"regexp"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
// Generate random IPv4 address
func randomIPv4() string {
return fmt.Sprintf("%d.%d.%d.%d",
rand.Intn(256),
rand.Intn(256),
rand.Intn(256),
rand.Intn(256))
}
// Generate random private IPv4 (RFC 1918)
func randomPrivateIPv4() string {
switch rand.Intn(3) {
case 0: // 10.0.0.0/8
return fmt.Sprintf("10.%d.%d.%d",
rand.Intn(256),
rand.Intn(256),
rand.Intn(256))
case 1: // 172.16.0.0/12
return fmt.Sprintf("172.%d.%d.%d",
rand.Intn(16)+16,
rand.Intn(256),
rand.Intn(256))
default: // 192.168.0.0/16
return fmt.Sprintf("192.168.%d.%d",
rand.Intn(256),
rand.Intn(256))
}
}
// Check if IP is private
func isPrivateIP(ip string) bool {
patterns := []string{
`^10\.`,
`^172\.(1[6-9]|2[0-9]|3[01])\.`,
`^192\.168\.`,
`^127\.`,
`^0\.`,
}
for _, pattern := range patterns {
matched, _ := regexp.MatchString(pattern, ip)
if matched {
return true
}
}
return false
}
// Generate random public IPv4
func randomPublicIPv4() string {
var ip string
for {
ip = randomIPv4()
if !isPrivateIP(ip) {
break
}
}
return ip
}
// Generate random IPv6 address
func randomIPv6() string {
parts := make([]string, 8)
for i := 0; i < 8; i++ {
parts[i] = fmt.Sprintf("%04x", rand.Intn(0x10000))
}
return fmt.Sprintf("%s:%s:%s:%s:%s:%s:%s:%s",
parts[0], parts[1], parts[2], parts[3],
parts[4], parts[5], parts[6], parts[7])
}
// Generate IPv4 with CIDR notation
func randomIPv4WithCIDR(minCIDR, maxCIDR int) string {
ip := randomIPv4()
cidr := rand.Intn(maxCIDR-minCIDR+1) + minCIDR
return fmt.Sprintf("%s/%d", ip, cidr)
}
// Validate IP address using net.ParseIP
func isValidIP(ipString string) bool {
return net.ParseIP(ipString) != nil
}
// Check if IP is private using net package
func isPrivateIPNet(ipString string) bool {
ip := net.ParseIP(ipString)
if ip == nil {
return false
}
privateRanges := []string{
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"127.0.0.0/8",
}
for _, cidr := range privateRanges {
_, subnet, _ := net.ParseCIDR(cidr)
if subnet.Contains(ip) {
return true
}
}
return false
}
// Generate multiple IP addresses
func generateIPAddresses(count int, ipType string) []string {
ips := make([]string, count)
for i := 0; i < count; i++ {
if ipType == "ipv6" {
ips[i] = randomIPv6()
} else {
ips[i] = randomIPv4()
}
}
return ips
}
func main() {
fmt.Println("Random IPv4:", randomIPv4())
fmt.Println("Private IPv4:", randomPrivateIPv4())
fmt.Println("Public IPv4:", randomPublicIPv4())
fmt.Println("IPv6:", randomIPv6())
fmt.Println("IPv4 with CIDR:", randomIPv4WithCIDR(8, 32))
batch := generateIPAddresses(5, "ipv4")
fmt.Printf("Batch: %s\n", batch)
fmt.Println("Is valid:", isValidIP("192.168.1.1"))
fmt.Println("Is private:", isPrivateIPNet("192.168.1.1"))
}
[EXPLANATION]
Go's rand.Intn(256) generates random octets, and fmt.Sprintf() formats IP addresses. The net package provides net.ParseIP() for validation and net.ParseCIDR() for subnet operations. The Contains() method checks if an IP belongs to a subnet, useful for detecting private ranges. For Go 1.20+, use rand.N(256) instead of rand.Intn(256). Remember to call rand.Seed(time.Now().UnixNano()) once at program start.
Expected Output
Random IPv4: 198.51.100.42 Private IPv4: 192.168.15.234 Public IPv4: 203.0.113.89 IPv6: 2001:0db8:85a3:0000:0000:8a2e:0370:7334 IPv4 with CIDR: 198.51.100.42/24 Batch: [203.0.113.15 198.51.100.89 192.0.2.45 198.51.100.123 203.0.113.67] Is valid: true Is private: true
Common Use Cases
- Generate test data for network microservices
- Mock IP addresses in API testing and benchmarks
- Create sample data for network monitoring tools
- Test IP-based rate limiting in web servers
- Populate network configuration structs with test data
Important Notes
-
net.ParseIP()accepts both IPv4 and IPv6 formats -
rand.Seed()should be called once at program start -
For concurrent usage, use
rand.New(rand.NewSource(seed))per goroutine -
Go 1.20+ introduces
rand.N()as a replacement forrand.Intn() -
net.IPtype provides many useful methods likeIsLoopback(),IsPrivate()
Try Our Interactive Generator
Don't want to write code? Use our free web-based Ip-addresses generator with instant results.
TRY IP-ADDRESSES GENERATOR →Other Programming Languages
View Ip-addresses generation code examples in PHP
View Ip-addresses generation code examples in JavaScript
View Ip-addresses generation code examples in Python
View Ip-addresses generation code examples in Java
View Ip-addresses generation code examples in C#
View Ip-addresses generation code examples in C++
View Ip-addresses generation code examples in Ruby