Menu Close

Go – How to get default IP mask of IP address in Go

Here, we will help you to understand how to get default IP mask of IP address in Go. We will learn about DefaultMask() method to get IP mask in go.

Function prototype:

func (ip IP) DefaultMask() IPMask

Return value:

DefaultMask() returns the default IP mask for the IP address ip. Only IPv4 addresses have default masks. DefaultMask() returns nil if ip is not a valid IPv4 address.

Example with code:

package main

import (
  "fmt"
  "net"
)


func main() {

    ip_addr := net.ParseIP("192.178.10.10")

    if ip_addr != nil {

        mask := ip_addr.DefaultMask()

        if mask != nil {

            fmt.Println("Default mask: ", mask)

        } else {

            fmt.Println("Getting default mask is failed")

        }
    } else {

        fmt.Println("Invalid IP address.")

    }

}

Output:

$ go run sample.go

Default mask: ffffff00

Example with invalid address name:

package main

import (
  "fmt"
  "net"
)


func main() {

    ip_addr := net.ParseIP("192.178.10.421")

    if ip_addr != nil {

        mask := ip_addr.DefaultMask()

        if mask != nil {

            fmt.Println("Default mask: ", mask)

        } else {

            fmt.Println("Getting default mask is failed")

        }
    } else {

        fmt.Println("Invalid IP address.")

    }

}

Output:

$: go run sample.go

Invalid IP address.

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

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

References:

https://golang.org/doc/
https://golang.org

Posted in golang, net

Leave a Reply

Your email address will not be published.

Contact Us