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 packagesimport ("net""fmt")func main(){// Call the IPv4Mask function for different IPv4 addressesfmt.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
netandfmtpackages. - Line 12: We call the
IPv4Maskfunction on the address255.255.255.0. The bitwiseANDof this address with the maskffffffffreturnsffffff00. - Line 13: We call the
IPv4Maskfunction on the address15.0.16.0. This address’s bitwiseANDwith the mask returns0f001000. - Line 14: Finally, we call the
IPv4Maskfunction on the address128.128.128.128. The bitwiseANDof this address with the mask returns80808080.