What is the net.IPv4 function in Golang?
The IPv4 function of the net package in Golang returns a 16-byte IP object that corresponds to a given set of bytes that represent an IPv4 address.
To use the IPv4 function, we first import the net package into our program, as shown below:
import (
"net"
)
Syntax
The syntax of the IPv4 function is shown below:
func IPv4(a, b, c, d byte) IP
Parameters
The IPv4 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 IPv4 function returns a 16-byte IP address that corresponds to the IPv4 address a.b.c.d.
Code
The code below shows how the IPv4 function works in Golang.
package main// Import the necessary packagesimport ("net""fmt")func main(){// Call the IPv4 function for different byte setsfmt.Println(net.IPv4(255, 255, 255, 0))fmt.Println(net.IPv4(15, 0, 16, 0))fmt.Println(net.IPv4(128, 128, 128, 128))}
Explanation
- Lines 4 to 7: We import the
netandfmtpackages. - Line 12: We call the
IPv4function on the byte set(255, 255, 255, 0). Consequently, the function returns an IP address in the forma.b.c.d, i.e.,255.255.255.0. - Line 13: We call the
IPv4function on the byte set(15, 0, 16, 0). The function returns the IP address15.0.16.0. - Line 14: We call the
IPv4function on the byte set(128, 128, 128, 128). The function returns the IP address128.128.128.128.