diff -r c3c188a0325a Lib/test/test_socket.py --- a/Lib/test/test_socket.py Thu Oct 11 17:22:45 2012 +0100 +++ b/Lib/test/test_socket.py Thu Oct 11 09:52:49 2012 -0700 @@ -726,6 +726,19 @@ if not fqhn in all_host_names: self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) + def testHostnameWhitespace(self): + hostnames = ( + '127.0.0.1 ', + ' 127.0.0.1', + ' 127.0.0.1 ', + ) + for hostname in hostnames: + try: + ip = socket.gethostbyname(hostname) + except socket.error: + self.fail('Failed to resolve %s' % hostname) + self.assertEqual(ip, '127.0.0.1') + @unittest.skipUnless(hasattr(socket, 'sethostname'), "test needs socket.sethostname()") @unittest.skipUnless(hasattr(socket, 'gethostname'), "test needs socket.gethostname()") def test_sethostname(self): diff -r c3c188a0325a Modules/socketmodule.c --- a/Modules/socketmodule.c Thu Oct 11 17:22:45 2012 +0100 +++ b/Modules/socketmodule.c Thu Oct 11 09:52:49 2012 -0700 @@ -788,6 +788,29 @@ #endif +/* Convenient function to trim whitespace from a string input */ +static char * +trimwhitespace(char *str) +{ + char *end, *cur; + + cur = str; + while (isspace(*cur)) + cur++; + + if (*cur == '\0') // str was ALL spaces + return str; // do nothing - will fail socket.gethostbyname(' ') + + end = cur + strlen(cur) - 1; + while (end > cur && isspace(*end)) + end--; + + *(end + 1) = '\0'; + + return cur; +} + + /* Convert a string specifying a host name or one of a few symbolic names to a numeric IP address. This usually calls gethostbyname() to do the work; the names "" and "" are special. @@ -801,6 +824,9 @@ int error; int d1, d2, d3, d4; char ch; + char *trimmed; + + trimmed = trimwhitespace(name); memset((void *) addr_ret, '\0', sizeof(*addr_ret)); if (name[0] == '\0') { @@ -865,7 +891,7 @@ sin->sin_addr.s_addr = INADDR_BROADCAST; return sizeof(sin->sin_addr); } - if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 && + if (sscanf(trimmed, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 && 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 && 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) { struct sockaddr_in *sin;