Menu Close

Go – SplitHostPort() function in net package in go

Here, we will learn about how to split network address into host and port in go by using SplitHostPort() function in net package in go.

SplitHostPort() function in net package splits a network address of the form “host:port“, “host%zone:port“, “[host]:port” or “[host%zone]:port” into host or host%zone and port.

If you want to split IPV6 address by using SplitHostPort() function then IPv6 address in hostport must be enclosed in square brackets, as in "[::1]:80", "[::1%lo0]:80".

Function prototype:

func SplitHostPort(hostport string) (host, port string, err error)

Return value:

host : Host address / name
port : Port number
err : Error message

Split IPv4 address having URL with port number by using SplitHostPort() function

URL can have either domain name or IP address along with port number.

Example with code:

package main

import (
    "fmt"
    "net"
)

func main() {
    host_port := "techieindoor.com:80"
    
    host, port, err := net.SplitHostPort(host_port)
    
    if err != nil {
        fmt.Println(err)
    }
    
    fmt.Println("Host: ", host, "\n", "Port: ", port)
}

Output:

Host: techieindoor.com
Port: 80

Suppose, you are passing complete URL to SplitHostPort() function. In that case, You will need to parse the URL and get the Host name. Pass this host to SplitHostPort(). For more details, Please check example given below:

Example with code:

package main

import (
    "fmt"
    "net"
    "net/url"
    "log"
)

func main() {
    url_str := "https://www.techieindoor.com:8000/go-net-package-in-go-golang/"
    
    url, err := url.Parse(url_str)
    
    if err != nil {
        log.Fatal(err)
    }
 
    host, port, err := net.SplitHostPort(url.Host)
    
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Println("Host: ", host, "\n", "Port: ", port)
}

Output

Host:  www.techieindoor.com 
Port:  8000

Parse IPv6 address with port number.

package main

import (
    "fmt"
    "net"
    "net/url"
    "log"
)

func main() {
    url_str := "http://[2001:db8::1]:8080/"
    
    url, err := url.Parse(url_str)
    
    if err != nil {
        log.Fatal(err)
    }
 
    host, port, err := net.SplitHostPort(url.Host)
    
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Println("Host: ", host, "\n", "Port: ", port)
}

Output:

Host:  2001:db8::1 
Port:  8080

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

https://www.techieindoor.com/category/golang/packages/net/

References:

https://golang.org/

Posted in Easy, golang, Level, net

Leave a Reply

Your email address will not be published.

Contact Us