Local IP address

506 days ago, 0 views.

Given the following HTTP server:

const { createServer } = require('http')
const { once } = require('events')

const server = createServer((req, res) => {
  res.end('Hello, World!')

const listen = async (...args) => {
  await once(server, 'listening')
  const { address, port, family } = server.address()
  return `http://${family === 'IPv6' ? `[${address}]` : address}:${port}/`

Promise.resolve().then(async () => {
  const url = await listen({ host: '', port: 3000 })
  console.log(`Listening at ${url}`)

There are different ways to expose it setting up host and port.

The (::1 in IPv6) is also called “loopback” or local-only interface.

# Listening at

curl # 'Hello, World!'
curl # nothing

That means server is actually not listening external request, all the stuff run in your computer. It’s used for putting servers running on production.


The localhost is actually an OS IPv4 alias for The IPv6 equivalent is [::]

It’s preferred to use the IP address rather than an alias since we don’t have control over it.

The (:: in IPv6) tells the server to listen listen on every available network interface.

It’s mainly used for listening request in your local network.

# Listening at

curl http://[::]:3000/ # 'Hello, World!'
curl http://[::1]:3000/ # 'Hello, World!'
curl # 'Hello, World!'
curl # 'Hello, World!'
curl # 'Hello, World!'

Note :: is not a valid URL by standard, but [::] is.

This is useful for accessing to the server using a different device connected over the same local network.

port 0

The port 0 is used to assign any available port determined by the OS.

Sometimes you want to do that after try for a preferred port.

try {
  return await listen({ host: '', port: 3000 })
} catch (error) {
  if (error.code !== 'EADDRINUSE') throw error
  return await listen({ host: '', port: 0 })
Kiko Beats

Kiko Beats