From 18196e66925c4bd5c766cc560d443ac7f34ded13 Mon Sep 17 00:00:00 2001 From: Vincent Sanders Date: Fri, 26 Nov 2010 15:36:27 +0000 Subject: Improve url_host_is_ip_address svn path=/trunk/netsurf/; revision=10951 --- utils/url.c | 48 +++++++++++++++++++----------------------------- 1 file changed, 19 insertions(+), 29 deletions(-) diff --git a/utils/url.c b/utils/url.c index cd731c97c..bc20e28e2 100644 --- a/utils/url.c +++ b/utils/url.c @@ -77,39 +77,29 @@ void url_init(void) /** - * Check whether a host is an IP address + * Check whether a host string is an IPv4 dotted quad address of the + * format XXX.XXX.XXX.XXX * - * \param host a hostname terminated by '\0' or '/' + * @todo This *should* be implemented with inet_pton but that requires + * implementing compatability glue for several operating systems. + * + * \param host a hostname terminated by '\0' or '/' * \return true if the hostname is an IP address, false otherwise */ bool url_host_is_ip_address(const char *host) { - int b; - bool n; - - assert(host); - - /* an IP address is of the format XXX.XXX.XXX.XXX, ie totally - * numeric with 3 full stops between the numbers */ - b = 0; // number of breaks - n = false; // number present - do { - if (*host == '.') { - if (!n) - return false; - b++; - n = false; - } else if ((*host == '\0') || (*host == '/')) { - if (!n) - return false; - /* todo: check the values are in 0-255 range */ - return (b == 3); - } else if (*host < '0' || *host > '9') { - return false; - } else { - n = true; - } - host++; - } while (1); + unsigned int b1, b2, b3, b4; + unsigned char c; + + if (strspn(host, "0123456789.") < strlen(host)) + return false; + + if (sscanf(host, "%3u.%3u.%3u.%3u%c", &b1, &b2, &b3, &b4, &c) != 4) + return false; + + if ((b1 > 255) || (b2 > 255) || (b3 > 255) || (b4 > 255)) + return false; + + return true; } /** -- cgit v1.2.3