server.address()


如果监听 IP 套接字,则返回操作系统报告的服务器的绑定 address、地址 family 名称和 port(用于在获取操作系统分配的地址时查找分配的端口):{ port: 12346, family: 'IPv4', address: '127.0.0.1' }

对于监听管道或 Unix 域套接字的服务器,名称作为字符串返回。

const server = net.createServer((socket) => {
  socket.end('goodbye\n');
}).on('error', (err) => {
  // 在这里处理错误。
  throw err;
});

// 获取任意未使用的端口。
server.listen(() => {
  console.log('opened server on', server.address());
});

server.address()'listening' 事件触发之前或调用 server.close() 之后返回 null

Returns the bound address, the address family name, and port of the server as reported by the operating system if listening on an IP socket (useful to find which port was assigned when getting an OS-assigned address): { port: 12346, family: 'IPv4', address: '127.0.0.1' }.

For a server listening on a pipe or Unix domain socket, the name is returned as a string.

const server = net.createServer((socket) => {
  socket.end('goodbye\n');
}).on('error', (err) => {
  // Handle errors here.
  throw err;
});

// Grab an arbitrary unused port.
server.listen(() => {
  console.log('opened server on', server.address());
});

server.address() returns null before the 'listening' event has been emitted or after calling server.close().