Search code examples
network-programmingwebserverportip-address

Why should a webserver listen to a specific port on all interfaces instead of just one specific interface?


This question follows from this (closed/redirected) question: express app server . listen all interfaces instead of localhost only

From that post, I now understand that the following code listens to port 3000 on all interfaces:

// helpers.mjs
const connectToDatabase = () => { 
  const dummyPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, 1000);
  });

  return dummyPromise;
};

export default connectToDatabase;
// app.mjs
import express from 'express'; 

import connectToDatabase from './helpers.mjs'

const app = express();

app.get('/', (req, res) => {
  res.send('<h2>Hi there!</h2>');
});

await connectToDatabase();

app.listen(3000);

I'm trying to fill in a big gap in my understanding on the relationship between IP addresses and ports. From this question, I learned a little about how an IP address is assigned to an interface. Further, I infer that an IP address has multiple ports (is it more correct for me to say "an interface has multiple ports"?).

My question is: as a webserver author, why would/should I bind to/listen at a specific port on every IP address as opposed to a that same port at one specific IP address?

E.g. the above code is a simple webserver that listens at 127.0.0.1:3000, 127.0.0.2:3000, 127.0.0.3:3000, etc.
Why is that desirable/convention/best practice? As opposed to listening specifically and only 127.0.0.14:3000?

Is this just that individual webserver developer's choice? Or is there a prevailing convention why you should listen to a specific port at every available IP address?

Like, the fact that host is an optional argument implies that there's a legit use-case where you'd want to listen at 127.0.0.1:3000, and 127.0.0.2:3000, and every other available ip_address:3000 -- why is that?


Solution

  • Every computer can have multiple IP addresses, one for each network interface. You usually don't care which network connection to your computer is being used by a user, so it makes sense to bind to to all of them.

    If you want to run a private web server (like for development testing) it might make sense to only bind to the localhost IP address. If you only bind to 127.0.0.1 then you will be able to view your website locally, but it won't be publicly available to others on your network.