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 =;
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("", 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();

    print("Connection received! {} is sending data.\n", .{client.address});

    const message = try, 1024);

    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, 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.

Last change: 2024-07-04, commit: e577a80