Techieindoor

Go – Convert IPv4 or IPv6 address to string in go

Here, We will learn how to convert IPv4 or IPv6 address to string in go. We can do it by using String() function in net package in go.

Basically, we use string() interface of IP type to convert IPv4 or IPv6 address to string in go.

Function prototype:

func (ip IP) String() string

Return value:

Example:

Example with code:

package main

import (
	"fmt"
	"net"
	"reflect"
)

func main() {
	// Convert IPv4 address to string
  ipv4_addr := net.IPv4(192, 168, 1, 10)
  ipv4_to_string := ipv4_addr.String()
  fmt.Print(ipv4_to_string)
  fmt.Println(" type:", reflect.TypeOf(ipv4_to_string))
    
    
  // Convert IPv4 address to string
  ipv4_addr = net.IPv4(10, 10, 1, 0)
  ipv4_to_string = ipv4_addr.String()
  fmt.Print(ipv4_to_string)
  fmt.Println(" type:", reflect.TypeOf(ipv4_to_string))
    
    
  // Convert IPv4 address to string
  ipv6_addr := net.IP{0xfd, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
  ipv6_to_string := ipv6_addr.String()
  fmt.Print(ipv6_to_string)
  fmt.Println(" type:", reflect.TypeOf(ipv6_to_string))
}

Output:

192.168.1.10 type: string

10.10.1.0 type: string

fd00:: type: string

To learn more about golang, Please refer given below link:

https://www.techieindoor.com/go-lang-tutorial/





References: https://golang.org/pkg/

Exit mobile version