Commit d15a0ec7b2

daurnimator <quae@daurnimator.com>
2020-12-02 01:13:59
Localhost is special (#6955)
* std: always return loopback address when looking up localhost * std: also return Ipv6 loopback * std: remove commented out obsolete code
1 parent 0858d7b
Changed files (1)
lib
lib/std/net.zig
@@ -19,9 +19,6 @@ pub const Address = extern union {
     in6: Ip6Address,
     un: if (has_unix_sockets) os.sockaddr_un else void,
 
-    // TODO this crashed the compiler. https://github.com/ziglang/zig/issues/3512
-    //pub const localhost = initIp4(parseIp4("127.0.0.1") catch unreachable, 0);
-
     /// Parse the given IP address string into an Address value.
     /// It is recommended to use `resolveIp` instead, to handle
     /// IPv6 link-local unix addresses.
@@ -839,6 +836,20 @@ fn linuxLookupName(
             if (addrs.items.len == 0) {
                 try linuxLookupNameFromDnsSearch(addrs, canon, name, family, port);
             }
+            if (addrs.items.len == 0) {
+                // RFC 6761 Section 6.3
+                // Name resolution APIs and libraries SHOULD recognize localhost
+                // names as special and SHOULD always return the IP loopback address
+                // for address queries and negative responses for all other query
+                // types.
+
+                // Check for equal to "localhost" or ends in ".localhost"
+                if (mem.endsWith(u8, name, "localhost") and (name.len == "localhost".len or name[name.len - "localhost".len] == '.')) {
+                    try addrs.append(LookupAddr{ .addr = .{ .in = Ip4Address.parse("127.0.0.1", port) catch unreachable } });
+                    try addrs.append(LookupAddr{ .addr = .{ .in6 = Ip6Address.parse("::1", port) catch unreachable } });
+                    return;
+                }
+            }
         }
     } else {
         try canon.resize(0);