node:net

Node.js net module, resolvable via both ESM import and CommonJS require. Sockets are real node:stream Duplex streams and servers are EventEmitters, both backed by the runtime's host TCP transport. A per-socket reader delivers inbound bytes onto the event loop; half-open connections, backpressure, and the DNS/Happy-Eyeballs dial sequence are handled for you.

javascript
import net from "node:net";
// or: const net = require("node:net");

const server = net.createServer((socket) => {
  socket.write("hello\n");
  socket.pipe(socket); // echo
});
server.listen(0, () => {
  const socket = net.connect(server.address().port, () => socket.end("hi"));
  socket.on("data", (d) => process.stdout.write(d));
});

Address helpers

FunctionResult
net.isIP(input)4 for an IPv4 string, 6 for IPv6 (incl. :: compression, v4-mapped tails, and a %zone scope suffix), 0 otherwise
net.isIPv4(input)true iff input is a valid IPv4 string
net.isIPv6(input)true iff input is a valid IPv6 string
javascript
net.isIP("127.0.0.1"); // → 4
net.isIP("::1"); // → 6
net.isIP("fe80::1%eth0"); // → 6
net.isIP("not-an-ip"); // → 0

net.Socket

net.Socket (alias net.Stream) is a Duplex stream over a TCP or Unix-domain connection. It can be called with or without new.

Creating and connecting

  • net.connect(...) / net.createConnection(...) — construct a Socket and begin connecting; both accept the same argument forms: - (port[, host][, connectListener]) - (path[, connectListener]) — Unix-domain socket - (options[, connectListener]) — an options object with port, host, path, timeout, noDelay, keepAlive, allowHalfOpen, highWaterMark, and related fields
  • socket.connect(...) — same argument forms, on an existing Socket.
host defaults to localhost. A name is resolved through the OS resolver and, when multiple addresses are returned, dialed using the Happy-Eyeballs sequence (see below). The 'lookup' event fires with the resolution result.

Events

'connect', 'ready', 'data', 'end', 'close' (with a hadError boolean), 'error', 'timeout', 'drain', 'lookup'.

Properties

connecting, pending, readyState ('opening' / 'open' / 'readOnly' / 'writeOnly' / 'closed'), bytesRead, bytesWritten (counts encoded bytes, including data buffered while still connecting), remoteAddress, remotePort, remoteFamily, localAddress, localPort, localFamily.

Methods

write(data[, encoding][, cb]), end([data][, encoding][, cb]), destroy([error]), resetAndDestroy(), destroySoon(), pause(), resume(), setEncoding(enc), setTimeout(ms[, cb]), setNoDelay([bool]), setKeepAlive([enable][, initialDelay]), ref(), unref(), address().

Half-open connections

With allowHalfOpen: false (the default), the writable side is shut down automatically once the readable side ends (peer FIN). Set allowHalfOpen: true to keep writing after the peer half-closes. A socket that has finished writing and has no reader consuming inbound data does not keep the process alive, matching Node.

javascript
const socket = net.connect({ port, allowHalfOpen: true });
socket.on("end", () => socket.end("bye")); // still writable after peer FIN

net.Server

net.createServer([options][, connectionListener]) returns a Server (EventEmitter). It can be called with or without new.
  • server.listen(port[, host][, backlog][, cb]), server.listen(path[, cb]) (Unix-domain), or server.listen(options[, cb]).
  • server.address(){ address, port, family } for a TCP server, or the path string for a Unix-domain server.
  • server.close([cb]), server.getConnections(cb), server.ref(), server.unref().
  • Events: 'listening', 'connection' (with the accepted Socket), 'close', 'error' (e.g. EADDRINUSE).
javascript
const server = net.createServer();
server.on("connection", (socket) => socket.end("welcome\n"));
server.listen(0, () => console.log("port", server.address().port));

Unix-domain sockets

Pass a path instead of port/host to either net.connect or server.listen. TCP-only socket options are skipped, and a missing path surfaces as ENOENT (an existing but unbound path as ECONNREFUSED).

javascript
const server = net.createServer().listen("/tmp/app.sock");
const client = net.connect("/tmp/app.sock");

net.BlockList

new net.BlockList() filters addresses by rule. Rules match case-insensitively on the address type.
  • addAddress(address[, type]), addRange(start, end[, type]), addSubnet(net, prefix[, type]), where type is "ipv4" (default) or "ipv6".
  • check(address[, type])true if the address matches any rule.
  • rules — the list of applied rules.

net.SocketAddress

new net.SocketAddress({ address, port, family, flowlabel }) — a value object describing an endpoint, with address, port, family, and flowlabel accessors, plus the static SocketAddress.parse(input).

Happy Eyeballs (auto-select family)

When a host resolves to both IPv4 and IPv6 addresses, connection attempts are interleaved by family and raced (RFC 8305), with a per-attempt timeout. The module-level defaults are configurable:

  • net.getDefaultAutoSelectFamily() / net.setDefaultAutoSelectFamily(bool)
  • net.getDefaultAutoSelectFamilyAttemptTimeout() / net.setDefaultAutoSelectFamilyAttemptTimeout(ms)

Per-connection overrides are accepted as autoSelectFamily / autoSelectFamilyAttemptTimeout in the connect options.

Not yet supported

  • TLS (node:tls) — the encrypted-socket layer is not yet implemented.
  • server.listen({ fd }) — adopting a pre-opened file descriptor.
  • Windows named pipes.

See also

  • Node.js upstream: