rafaelmaeuer
3/2/2020 - 10:46 PM

Parse IP from string to IPv4 in Go

func parseIPv4(ipv4Str string) (net.IP, error) {
	// Parse as a naked IPv4 address
	ip := net.ParseIP(ipv4Str)
	if ip == nil{
		err := fmt.Errorf("Unable to parse %+q to an IPv4 address", ipv4Str)
		return nil, err
	}
	
	ipv4 := ip.To4()
	if ipv4 == nil {
		err := fmt.Errorf("Unable to string convert %+q to an IPv4 address", ipv4Str)
		return nil, err
	}
	
	return ipv4, nil
}