Menu Close

Go – IsPrivate() of net package in go

IsPrivate() function is used to check whether IP is a private address or not. IsPrivate() function is of net package.

function prototype:

func (ip IP) IsPrivate() bool

Return type:

IsPrivate() of net package in go returns true if IP address is a private address else false.

Example:

package main

import (
	"fmt"
	"net"
)

func main() {
    // Check IPv4 address is a private IP or not
    ipv4_ip := net.ParseIP("10.10.10.2")
    is_private_addr := ipv4_ip.IsPrivate()
    
    if is_private_addr == true {
        fmt.Println("10.10.10.2 is a private IP address.")
    } else {
        fmt.Println("10.10.10.2 is not a private IP address.")
    }
    
    ipv4_ip = net.ParseIP("11.0.0.0")
    is_private_addr = ipv4_ip.IsPrivate()
    
    if is_private_addr == true {
        fmt.Println("11.0.0.0 is a private IP address.")
    } else {
        fmt.Println("11.0.0.0 is not a private IP address.")
    }
    
    // Check IPv6 address is a private IP or not
    ipv6_ip := net.ParseIP("fc00::")
    is_private_addr = ipv6_ip.IsPrivate()
    
    if is_private_addr == true {
        fmt.Println("fc00:: is a private IPv6 address.")
    } else {
        fmt.Println("fc00:: is not a private IPv6 address.")
    }
    
    ipv6_ip = net.ParseIP("fe00::")
    is_private_addr = ipv6_ip.IsPrivate()
    
    if is_private_addr == true {
        fmt.Println("fe00:: is a private IPv6 address.")
    } else {
        fmt.Println("fe00:: is not a private IPv6 address.")
    }
}

Output:

10.10.10.2 is a private IP address.
11.0.0.0 is not a private IP address.
fc00:: is a private IPv6 address.
fe00:: is not a private IPv6 address.

To learn more about golang, Please refer given below link:

https://www.techieindoor.com/go-lang-tutorial/

References: https://golang.org/pkg/

Posted in golang, net, packages

Leave a Reply

Your email address will not be published. Required fields are marked *