diff options
Diffstat (limited to 'net/base')
-rw-r--r-- | net/base/net_util.cc | 21 | ||||
-rw-r--r-- | net/base/net_util.h | 3 | ||||
-rw-r--r-- | net/base/net_util_unittest.cc | 8 |
3 files changed, 29 insertions, 3 deletions
diff --git a/net/base/net_util.cc b/net/base/net_util.cc index 7527b6c..b88a3bf 100644 --- a/net/base/net_util.cc +++ b/net/base/net_util.cc @@ -991,7 +991,7 @@ bool GetHostAndPort(std::string::const_iterator host_and_port_begin, if (!hostname_component.is_nonempty()) return false; // Failed parsing. - + int parsed_port_number = -1; if (port_component.is_nonempty()) { parsed_port_number = url_parse::ParsePort(auth_begin, port_component); @@ -1008,7 +1008,7 @@ bool GetHostAndPort(std::string::const_iterator host_and_port_begin, // Pass results back to caller. host->assign(auth_begin + hostname_component.begin, hostname_component.len); *port = parsed_port_number; - + return true; // Success. } @@ -1031,9 +1031,24 @@ std::string NetAddressToString(const struct addrinfo* net_address) { if (result != 0) { DLOG(INFO) << "getnameinfo() failed with " << result; - return std::string(); + buffer[0] = '\0'; } + return std::string(buffer); +} +std::string GetMyHostName() { +#if defined(OS_WIN) + EnsureWinsockInit(); +#endif + + // Maximum size of 256 is somewhat arbitrary. Mozilla uses a size of 100 + // so this should cover the majority of cases. + char buffer[256]; + int result = gethostname(buffer, sizeof(buffer)); + if (result != 0) { + DLOG(INFO) << "gethostname() failed with " << result; + buffer[0] = '\0'; + } return std::string(buffer); } diff --git a/net/base/net_util.h b/net/base/net_util.h index 6f3c1ff..014a83d 100644 --- a/net/base/net_util.h +++ b/net/base/net_util.h @@ -58,6 +58,9 @@ bool GetHostAndPort(const std::string& host_and_port, // Returns empty string on failure. std::string NetAddressToString(const struct addrinfo* net_address); +// Returns the hostname of the current system. Returns empty string on failure. +std::string GetMyHostName(); + // Return the value of the HTTP response header with name 'name'. 'headers' // should be in the format that URLRequest::GetResponseHeaders() returns. // Returns the empty string if the header is not found. diff --git a/net/base/net_util_unittest.cc b/net/base/net_util_unittest.cc index 2293368..c4083dc 100644 --- a/net/base/net_util_unittest.cc +++ b/net/base/net_util_unittest.cc @@ -869,3 +869,11 @@ TEST(NetUtilTest, DISABLED_NetAddressToString_IPv6) { EXPECT_EQ(std::string(tests[i].result), result); } } + +TEST(NetUtilTest, GetMyHostName) { + // We can't check the result of GetMyHostName() directly, since the result + // will differ across machines. Our goal here is to simply exercise the + // code path, and check that things "look about right". + std::string my_hostname = net::GetMyHostName(); + EXPECT_FALSE(my_hostname.empty()); +} |