The ParseIP()
function of the net
package in Golang parses a given
To use the ParseIP()
function, we first import the net
package into our program, as shown below:
import (
"net"
)
The syntax of the ParseIP()
function is shown below:
func ParseIP(string) IP
The ParseIP()
function accepts a single mandatory parameter, that is, the string to parse.
The string can be in any of the following forms:
IPv4 dotted-decimal, for example, (“192.0.2.1”)
IPv6, for example, (“2001:db8::68”)
IPv4-mapped IPv6, ("::ffff:192.0.2.1")
The ParseIP()
function returns an object of type IP that represents the IP address of the parsed string.
If the given string is not a valid representation of an IP address, the ParseIP()
function returns nil
.
The code below shows how the ParseIP()
function works in Golang:
package main// import necessary packagesimport ("net""fmt")func main(){// initilaize strings to represent IP AddressesaddressOne := "192.168.8.0"addressTwo := "2001:cb8::17"addressThree := "2.3.1"// Parse each string for IPfmt.Println(net.ParseIP(addressOne))fmt.Println(net.ParseIP(addressTwo))fmt.Println(net.ParseIP(addressThree))}
In the code above:
Lines 4 to 7: We import the net
and fmt
packages.
Lines 12 to 14: We initialize three unique strings, each of which represents an IP address.
Lines 17 to 18: The net.ParseIP
function is called on the strings addressOne
and addressTwo
. As both strings are valid textual representations of an IP address, the corresponding IP
object is printed.
Line 19: The net.ParseIP
function is called on a string that is not a valid textual representation of an IP address. Consequently, the function returns nil
.