Golang – Check if IPv4 is valid and resolve FQDN

This recipe demonstrates if string is a valid IPv4, and also to resolve a FQDN to IP address.

This recipe uses os.Args to get the second argument as FQDN and call net.ResolveIPAddr() function to do a FQDN resolution to IP address.

package main

import (

func isIPv4Addr(ip string) bool {
	if net.ParseIP(ip) == nil {
		// invalid ipv4 address
		return false
	return true

func resolve(fqdn string) string {
	// net.ResolveIPAddr() accepts two arguments: net is one of these "ip", "ip4", "ip6" and a fqdn
	i, e := net.ResolveIPAddr("ip", fqdn)
	if e != nil {
	// return the string of the ip address pointer.
	return i.String()

func main() {
	if len(os.Args) != 2 {
		// command line requires the program name and fqdn, which will be two indices in string slice.
		log.Fatalf("Usage example: %s www.google.com", os.Args[0])


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s