How to parse a string into a net.Addr in Golang

How to Parse a string into a net.Addr in Golang

In this article we are going to see how to parse a simple Go string into a Golang net.Addr type. First let’s have a look at the net.Addr type and how it looks like

type Addr interface {
    Network() string // name of the network (for example, "tcp", "udp")
    String()  // string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80") }

The net.Addr is just an interface, so any type that satisfies this interface is a valid net.Addr. Valid examples of this are

They all implement the net.Addr interface because they have the Network and String methods. If you take note, all of thee types have a function to parse a string into their concrete type. For net.UDPAddr we have net.ResolveUDPAddr, for net.TCPAddr we have net.ResolveTCPAddr and for net.IPAddr we have net.ResolveIPAddr

How to parse string into net.TCPAddr

By using the function from the standard library for net.TCPAddr, net.ResolveTCPAddr as illustrated below

func ResolveTCPAddr(network, address string) *TCPAddr, error

Please check how to use net.ResolveTCPAddr in the example below

package main

import (
	"fmt"
	"net"
)

func main() {
	addr, err := net.ResolveTCPAddr("tcp", "1.1.1.1:1234")
	if err != nil {
		panic(err)
	}
	fmt.Println("Addr", addr.String())
}

You can run the code yourself by using the Go playground https://go.dev/play/p/ukobauySIbe

How to parse string into net.TCPAddr

By using the function from the standard library for net.UDPAddr, net.ResolveUDPAddr as illustrated below

func ResolveUDPAddr(network, address string) *UDPAddr, error

Please check how to use net.ResolveUDPAddr in the example below

package main

import (
	"fmt"
	"net"
)

func main() {
	addr, err := net.ResolveUDPAddr("tcp", "1.1.1.1:53")
	if err != nil {
		panic(err)
	}
	fmt.Println("Addr", addr.String())
}

You can run the code yourself by using the Go playground https://go.dev/play/p/d2toJPjtXiN

How to parse string into net.IPAddr

By using the function from the standard library for net.IPAddr, net.ResolveIPAddr as illustrated below

func ResolveIPAddr(network, address string) *IPAddr, error

Please check how to use net.ResolveIPAddr in the example below

package main

import (
	"fmt"
	"net"
)

func main() {
	addr, err := net.ResolveIPAddr("ip", "1.1.1.1")
	if err != nil {
		panic(err)
	}
	fmt.Println("Addr", addr.String())
}

You can run the code yourself by using the Go playground https://go.dev/play/p/PM-KOzep-ty

Join the Golang Developers Community on Golang Cafe