Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Validate an IP address in GO

Posted on February 4, 2020February 4, 2020 by admin

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
  • ipv6
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme