authorgravatar for frmdstryr@protonmail.comfrmdstryr <frmdstryr@protonmail.com> 2019-11-18 08:45:25-05:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2019-11-19 01:06:04+00:00
logaa4e92f3b3dc4b349eeabf589f8b9047e7342f03
treefbf901edba030c004fa71eba75c6874cb38be95b
parented956b581283824da1f7d39b953f4d716928eee2

Make StreamServer return address of accecpted client


2 files changed, 13 insertions(+), 5 deletions(-)

lib/std/net.zig+11-3
...@@ -1360,14 +1360,22 @@ pub const StreamServer = struct {...@@ -1360,14 +1360,22 @@ pub const StreamServer = struct {
1360 BlockedByFirewall,1360 BlockedByFirewall,
1361 } || os.UnexpectedError;1361 } || os.UnexpectedError;
13621362
1363 /// If this function succeeds, the returned `fs.File` is a caller-managed resource.1363 pub const Connection = struct {
1364 pub fn accept(self: *StreamServer) AcceptError!fs.File {1364 file: fs.File,
1365 address: Address
1366 };
1367
1368 /// If this function succeeds, the returned `Connection` is a caller-managed resource.
1369 pub fn accept(self: *StreamServer) AcceptError!Connection {
1365 const nonblock = if (std.io.is_async) os.SOCK_NONBLOCK else 0;1370 const nonblock = if (std.io.is_async) os.SOCK_NONBLOCK else 0;
1366 const accept_flags = nonblock | os.SOCK_CLOEXEC;1371 const accept_flags = nonblock | os.SOCK_CLOEXEC;
1367 var accepted_addr: Address = undefined;1372 var accepted_addr: Address = undefined;
1368 var adr_len: os.socklen_t = @sizeOf(Address);1373 var adr_len: os.socklen_t = @sizeOf(Address);
1369 if (os.accept4(self.sockfd.?, &accepted_addr.any, &adr_len, accept_flags)) |fd| {1374 if (os.accept4(self.sockfd.?, &accepted_addr.any, &adr_len, accept_flags)) |fd| {
1370 return fs.File.openHandle(fd);1375 return Connection{
1376 .file = fs.File.openHandle(fd),
1377 .address = accepted_addr,
1378 };
1371 } else |err| switch (err) {1379 } else |err| switch (err) {
1372 // We only give SOCK_NONBLOCK when I/O mode is async, in which case this error1380 // We only give SOCK_NONBLOCK when I/O mode is async, in which case this error
1373 // is handled by os.accept4.1381 // is handled by os.accept4.
lib/std/net/test.zig+2-2
...@@ -115,8 +115,8 @@ fn testClient(addr: net.Address) anyerror!void {...@@ -115,8 +115,8 @@ fn testClient(addr: net.Address) anyerror!void {
115}115}
116116
117fn testServer(server: *net.StreamServer) anyerror!void {117fn testServer(server: *net.StreamServer) anyerror!void {
118 var client_file = try server.accept();118 var client = try server.accept();
119119
120 const stream = &client_file.outStream().stream;120 const stream = &client.file.outStream().stream;
121 try stream.print("hello from server\n");121 try stream.print("hello from server\n");
122}122}