forum icon indicating copy to clipboard operation
forum copied to clipboard

【Zig 日报】监听未使用的 TCP 端口

Open jiacai2050 opened this issue 9 months ago • 0 comments

在本例中,端口会显示在控制台中,程序会一直监听,直到有请求提出。 当端口设置为 0 时,Ip4Address 会随机分配一个端口。

//! 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 });
}

启动时,请尝试进行如下测试:

echo "hello zig" | nc localhost <port> 

默认情况下,程序以 IPv4 方式监听。 | nc localhost 默认情况下,程序使用 IPv4 监听。 如果要使用 IPv6,请使用 ::1 代替 127.0.0.1,将 net.Ip4Address.parse 替换为 net.Ip6Address.parse,并将 net.Address 创建中的 .in 字段替换为 .in6。

加入我们

Zig 中文社区是一个开放的组织,我们致力于推广 Zig 在中文群体中的使用,有多种方式可以参与进来:

  1. 供稿,分享自己使用 Zig 的心得
  2. 改进 ZigCC 组织下的开源项目
  3. 加入微信群

jiacai2050 avatar Jan 27 '25 14:01 jiacai2050