What is the net.IPv4Mask function in Golang?

The IPv4Mask function of the net package in Golang returns a 4-byte IPMask object that corresponds to a given set of bytes that represent an IPv4 address.

To use the IPv4Mask function, we first import the net package into our program, as shown below:

import (
   "net"
)

Syntax

The syntax of the IPv4Mask function is shown below:

func IPv4Mask(a, b, c, d byte) IPMask

Parameters

The IPv4Mask function accepts 4 byte objects with values between 0 and 255. These parameters are then combined to form an IPv4 address of the form a.b.c.d.

Return value

The IPv4Mask function returns an IPMask object that corresponds to the IPv4 address a.b.c.d. It does this by performing a bitwise AND operation of the IPv4 address with the mask ffffffff.

Code

The code below shows how the IPv4Mask function works in Golang.

package main
// Import the necessary packages
import (
"net"
"fmt"
)
func main(){
// Call the IPv4Mask function for different IPv4 addresses
fmt.Println(net.IPv4Mask(255, 255, 255, 0))
fmt.Println(net.IPv4Mask(15, 0, 16, 0))
fmt.Println(net.IPv4Mask(128, 128, 128, 128))
}

Explanation

  • Lines 4 to 7: We import the net and fmt packages.
  • Line 12: We call the IPv4Mask function on the address 255.255.255.0. The bitwise AND of this address with the mask ffffffff returns ffffff00.
  • Line 13: We call the IPv4Mask function on the address 15.0.16.0. This address’s bitwise AND with the mask returns 0f001000.
  • Line 14: Finally, we call the IPv4Mask function on the address 128.128.128.128. The bitwise AND of this address with the mask returns 80808080.