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 (
"fmt"
"log"
"net"
"os"
)
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 {
log.Fatal(e)
}
// 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])
}
fmt.Println(resolve(os.Args[1]))
}