authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-06-07 13:53:12-04:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2020-06-07 13:53:12-04:00
log37695ed81e638de864a002295aa08a35297a862b
tree2e88fe63dc386fab3afe04773c9d520a57ac6196
parent499df9680ceea203602ba1aebc475b047714dbf4
parenta6d1ef64d753f8be59d68695f927e03777bb6514
signature Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #5556 from iansimonson/try_other_addresses

tcpConnectToHost try all addresses in AddressList

2 files changed, 47 insertions(+), 1 deletions(-)

lib/std/net.zig+9-1
......@@ -573,7 +573,15 @@ pub fn tcpConnectToHost(allocator: *mem.Allocator, name: []const u8, port: u16)
573573
574574 if (list.addrs.len == 0) return error.UnknownHostName;
575575
576 return tcpConnectToAddress(list.addrs[0]);
576 for (list.addrs) |addr| {
577 return tcpConnectToAddress(addr) catch |err| switch (err) {
578 error.ConnectionRefused => {
579 continue;
580 },
581 else => return err,
582 };
583 }
584 return std.os.ConnectError.ConnectionRefused;
577585}
578586
579587pub fn tcpConnectToAddress(address: Address) !fs.File {
lib/std/net/test.zig+38
......@@ -130,6 +130,44 @@ test "listen on a port, send bytes, receive bytes" {
130130 try await client_frame;
131131}
132132
133test "listen on ipv4 try connect on ipv6 then ipv4" {
134 if (!std.io.is_async) return error.SkipZigTest;
135
136 if (std.builtin.os.tag != .linux and !std.builtin.os.tag.isDarwin()) {
137 // TODO build abstractions for other operating systems
138 return error.SkipZigTest;
139 }
140
141 // TODO doing this at comptime crashed the compiler
142 const localhost = try net.Address.parseIp("127.0.0.1", 0);
143
144 var server = net.StreamServer.init(net.StreamServer.Options{});
145 defer server.deinit();
146 try server.listen(localhost);
147
148 var server_frame = async testServer(&server);
149 var client_frame = async testClientToHost(
150 testing.allocator,
151 "localhost",
152 server.listen_address.getPort(),
153 );
154
155 try await server_frame;
156 try await client_frame;
157}
158
159fn testClientToHost(allocator: *mem.Allocator, name: []const u8, port: u16) anyerror!void {
160 if (builtin.os.tag == .wasi) return error.SkipZigTest;
161
162 const connection = try net.tcpConnectToHost(allocator, name, port);
163 defer connection.close();
164
165 var buf: [100]u8 = undefined;
166 const len = try connection.read(&buf);
167 const msg = buf[0..len];
168 testing.expect(mem.eql(u8, msg, "hello from server\n"));
169}
170
133171fn testClient(addr: net.Address) anyerror!void {
134172 if (builtin.os.tag == .wasi) return error.SkipZigTest;
135173