ipv6 Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/ipv6/ Tue, 04 Feb 2020 14:56:30 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 ipv6 Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/ipv6/ 32 32 159787465 Validate an IP address in GO https://vikasboss.github.io/validate-an-ip-address-in-go/ https://vikasboss.github.io/validate-an-ip-address-in-go/#respond Tue, 04 Feb 2020 14:56:24 +0000 https://vikasboss.github.io/?p=1367 ParseIP function of the net package can be used to validate an IP address. The same function can be used to validate both IPV4 and IPV6 addresses. Below is the signature of...

The post Validate an IP address in GO appeared first on Welcome To Golang By Example.

]]>
ParseIP function of the net package can be used to validate an IP address. The same function can be used to validate both IPV4 and IPV6 addresses. Below is the signature of the function

func ParseIP(s string) IP

https://golang.org/pkg/net/#ParseIP

The ParseIP function

  • Returns nil if the given IP address is not valid
  • Else it creates an instance of IP struct and returns that.

Let’s see a working code:

package main

import (
    "fmt"
    "net"
)

func main() {
    validIPV4 := "10.40.210.253"
    
    checkIPAddress(validIPV4)

    invalidIPV4 := "1000.40.210.253"
    checkIPAddress(invalidIPV4)

    valiIPV6 := "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
    checkIPAddress(valiIPV6)

    invalidIPV6 := "2001:0db8:85a3:0000:0000:8a2e:0370:7334:3445"
    checkIPAddress(invalidIPV6)
}

func checkIPAddress(ip string) {
    if net.ParseIP(ip) == nil {
        fmt.Printf("IP Address: %s - Invalid\n", ip)
    } else {
        fmt.Printf("IP Address: %s - Valid\n", ip)
    }
}

Output:

IP Address: 10.40.210.253 - Valid
IP Address: 1000.40.210.253 - Invalid
IP Address: 2001:0db8:85a3:0000:0000:8a2e:0370:7334 - Valid
IP Address: 2001:0db8:85a3:0000:0000:8a2e:0370:7334:3445 - Invalid

The post Validate an IP address in GO appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/validate-an-ip-address-in-go/feed/ 0 1367