Go Build Example with Net package
Go Build with Net package
The package net
defines many types, functions and methods of use in Go network programming. The type IP is defined as an array of bytes
type IP []byte
There are several functions to manipulate a variable of type IP, but you are likely to use only some of them in practice. For example, the function ParseIP(String)
will take a dotted IPv4 address or a colon IPv6 address, while the IP method String will return a string.
pradeep:~$cat ip.go
/* IP
*/
package main
import (
"net"
"os"
"fmt"
)
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s ip-addr\n", os.Args[0])
os.Exit(1)
}
name := os.Args[1]
addr := net.ParseIP(name)
if addr == nil {
fmt.Println("Invalid address")
} else {
fmt.Println("The address is ", addr.String())
}
os.Exit(0)
}
So far we have been using go run
to compile and run our Go
code.
pradeep:~$go run ip.go
Usage: /var/folders/cf/vzmh318x285f0c1sbsnm14m40000gn/T/go-build3102043780/b001/exe/ip ip-addr
exit status 1
pradeep:~$go run ip.go ip 127.0.0.1
Usage: /var/folders/cf/vzmh318x285f0c1sbsnm14m40000gn/T/go-build1045950479/b001/exe/ip ip-addr
exit status 1
Lets build this time.
pradeep:~$go build ip.go
As a result of the go build
command, we can see a new file with the name of the package.
pradeep:~$ls -la | grep ip
-rwxr-xr-x 1 pradeep staff 1997584 Apr 30 16:59 ip
-rw-r--r-- 1 pradeep staff 402 Apr 30 16:58 ip.go
pradeep:~$
Let us call this code ip
pradeep:~$ip 127.0.0.1
zsh: command not found: ip
Indicate that we are referring to the ip
in the current directory by using ./
pradeep:~$./ip 127.0.0.1
The address is 127.0.0.1
pradeep:~$./ip 192.168.1.567
Invalid address
pradeep:~$./ip 192.168.1.5
The address is 192.168.1.5
An example IPv6 address
pradeep:~$./ip 2003:abcd:ef::12
The address is 2003:abcd:ef::12
pradeep:~$cat mask.go
package main
import (
"fmt"
"net"
"os"
)
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s dotted-ip-addr\n", os.Args[0])
os.Exit(1)
}
dotAddr := os.Args[1]
addr := net.ParseIP(dotAddr)
if addr == nil {
fmt.Println("Invalid address")
os.Exit(1)
}
mask := addr.DefaultMask()
network := addr.Mask(mask)
ones, bits := mask.Size()
fmt.Println("Address is ", addr.String(),
" Default mask length is ", bits,
"Leading ones count is ", ones,
"Mask is (hex) ", mask.String(),
" Network is ", network.String())
os.Exit(0)
}
pradeep:~$go build mask.go
pradeep:~$./mask 192.168.1.5
Address is 192.168.1.5 Default mask length is 32 Leading ones count is 24 Mask is (hex) ffffff00 Network is 192.168.1.0
pradeep:~$./mask 10.20.30.5
Address is 10.20.30.5 Default mask length is 32 Leading ones count is 8 Mask is (hex) ff000000 Network is 10.0.0.0
pradeep:~$./mask 172.16.1.5
Address is 172.16.1.5 Default mask length is 32 Leading ones count is 16 Mask is (hex) ffff0000 Network is 172.16.0.0