Menu Close

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:

  • It returns nil if ip has 0 length.
  • It returns dotted decimal (“10.10.10.0”), If ip is an IPv4 address.
  • IPv6 address conforming to “2002:db8::1”, if ip is a valid IPv6 address
  • It returns hexadecimal form of ip, without punctuation, if no other cases apply

Example:

  • Suppose you want to convert 10.10.10.10 IPv4 address to string and also validate the IPv4 address at the same time.
  • Then, first you have convert this IP to IPv4 or IPv6 address which accept 4-byte (IPv4) or 16-byte (IPv6) slices as input in IPv4() or IP function of net package respectively.
  • Then by using String interface of IPv4 address, we can convert IP address to string.

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/

Posted in golang, net, packages

Leave a Reply

Your email address will not be published. Required fields are marked *