Listen on unused port TCP/IP
In this example, the port is displayed on the console, and the program will
listen until a request is made. Ip4Address
assigns a random port when
setting port to 0.
//! Start a TCP server at an unused port.
//!
//! Test with
//! echo "hello zig" | nc localhost <port>
const std = @import("std");
const net = std.net;
const print = std.debug.print;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const loopback = try net.Ip4Address.parse("127.0.0.1", 0);
const localhost = net.Address{ .in = loopback };
var server = try localhost.listen(.{
.reuse_port = true,
});
defer server.deinit();
const addr = server.listen_address;
print("Listening on {}, access this port to end the program\n", .{addr.getPort()});
var client = try server.accept();
defer client.stream.close();
print("Connection received! {} is sending data.\n", .{client.address});
const message = try client.stream.reader().readAllAlloc(allocator, 1024);
defer allocator.free(message);
print("{} says {s}\n", .{ client.address, message });
}
When start starts up, try test like this:
echo "hello zig" | nc localhost <port>
By default, the program listens with IPv4. If you want IPv6, use ::1
instead of 127.0.0.1
, replace net.Ip4Address.parse
by
net.Ip6Address.parse
and the field .in
in the creation of the
net.Address
with .in6
.
(And connect to something like ip6-localhost
, depending on the way
your machine is set up.)
The next section will show how to connect to this server using Zig code.