Skip to main content
On this page

@std/net

Overview Jump to heading

Network utilities.

import { getAvailablePort } from "@std/net";

const command = new Deno.Command(Deno.execPath(), {
 args: ["test.ts", "--port", getAvailablePort().toString()],
});

// ...

Add to your project Jump to heading

deno add jsr:@std/net

See all symbols in @std/net on

什么是 @std/net? Jump to heading

用于辅助完成常见网络任务的工具,补充 Deno 核心 API:

  • 查找或预留一个开放端口。
  • 发现机器的 LAN 地址以绑定服务器。
  • 验证 IP 版本,并检查地址是否属于 CIDR 子网。

为什么使用 @std/net? Jump to heading

  • 选择安全的端口和接口:
    • 当你控制监听器时,优先使用 Deno.listen({ port: 0 }) 来获取临时端口。
    • 当你需要在绑定之前给其他进程传递空闲端口值时,使用 getAvailablePort()(然后立即绑定以避免竞态)。
  • 绑定到合适的网络:使用 getNetworkAddress() 在 LAN 的 IPv4 或 IPv6 地址上服务,而非回环地址。
  • 验证并筛选流量:isIPv4/isIPv6match*Subnet 辅助函数让你可以根据 IP 范围构建允许/拒绝列表或功能开关。

示例 Jump to heading

const listener = Deno.listen({ hostname: "127.0.0.1", port: 0 });
const { port } = listener.addr as Deno.NetAddr;
// 在 listener 上启动服务器 ...

绑定到 LAN 地址(不仅限于 localhost) Jump to heading

import { getNetworkAddress } from "@std/net/unstable-get-network-address";

const hostname = getNetworkAddress() ?? "127.0.0.1"; // 默认 IPv4
Deno.serve({ hostname, port: 0 }, () => new Response("来自 LAN 的问候"));

验证传入的 IP 类型 Jump to heading

import { isIPv4, isIPv6 } from "@std/net/unstable-ip";

function describe(ip: string): string {
  if (isIPv4(ip)) return "IPv4";
  if (isIPv6(ip)) return "IPv6";
  return "未知";
}

通过子网允许请求(支持 IPv4 和 IPv6) Jump to heading

import { matchSubnets } from "@std/net/unstable-ip";

const allowlist = [
  "192.168.1.0/24", // 家庭局域网
  "2001:db8::/64", // 文档示例 IPv6 前缀
];

Deno.serve((req, info) => {
  const ip = (info.remoteAddr as Deno.NetAddr).hostname;
  if (!matchSubnets(ip, allowlist)) {
    return new Response("禁止访问", { status: 403 });
  }
  return new Response("通过");
});

传递空闲端口给子进程 Jump to heading

import { getAvailablePort } from "@std/net";

const port = getAvailablePort();
// 如果可能,立即在本进程中预留该端口以避免竞态
const listener = Deno.listen({ hostname: "127.0.0.1", port });

const child = new Deno.Command("deno", {
  args: ["run", "--allow-net", "./child_server.ts", String(port)],
});
child.spawn();

小贴士 Jump to heading

  • 尽可能优先使用 Deno.listen({ port: 0 });仅当必须先将端口值传给其他进程时才使用 getAvailablePort()
  • 获得端口号后,应立即在同一进程中绑定,避免 TOCTOU 竞态条件。
  • unstable-ip 辅助函数非常适合制作允许/拒绝列表,但避免仅依赖客户端可控的头如 X-Forwarded-For 来实现完整访问控制。

你找到了你需要的东西吗?

编辑此页面
隐私政策