Golang net.IP.Mask(), String(), To16() and To4() functions example

package net

Golang net.IP.Mask(), String(), To16() and To4() functions usage example

 package main

 import (
 "fmt"
 "net"
 "os"
 )

 func main() {

 hostname := "www.golang.org"

 IPAddr, err := net.ResolveIPAddr("ip", hostname)
 if err != nil {
 fmt.Println("Error in resolving IP")
 os.Exit(1)
 }

 addr := net.ParseIP(IPAddr.String())

 if addr == nil {
 fmt.Println("Invalid address")
 os.Exit(1)
 }
 mask := addr.DefaultMask()
 network := addr.Mask(mask)

 fmt.Printf("Address : %s \nNetwork : %s \n", addr.String(), network.String())

 // convert addr IP address to 16-byte
 十六IP := addr.To16()
 fmt.Printf("16 byte representation : %s\n", 十六IP.String())

 // convert network IP address to 16-byte
 四IP := addr.To4()
 fmt.Printf("4 byte representation : %s\n", 四IP.String())

 }

Sample output :

Address : 74.125.200.141

Network : 74.0.0.0

16 byte representation : 74.125.200.141

4 byte representation : 74.125.200.141

References :

http://golang.org/pkg/net/#IP.Mask

http://golang.org/pkg/net/#IP.String

http://golang.org/pkg/net/#IP.To16

http://golang.org/pkg/net/#IP.To4

Advertisement