Network comprehension question: localhost vs. local IP address

Colin Watson cjwatson at ubuntu.com
Tue Jun 13 23:19:00 UTC 2017


On Tue, Jun 13, 2017 at 08:46:46PM +0200, Volker Wysk wrote:
> Now I'm puzzled. What is the difference between localhost and 192.168.178.20? 

A host has some number of network interfaces, each of which has various
properties such as addresses and netmasks.  Some network interfaces
correspond to physical network ports: for example, "eth0" is one likely
name for the first Ethernet adapter.  However, some other network
interfaces are virtual concepts that exist only in the operating
system's mind.  These are useful for various purposes, such as messages
sent to other processes on the local system, bridging between virtual
machines, tunnels, and so on.

One of these virtual network interfaces is "lo", the loopback interface.
Packets transmitted on this interface always come back to the local
machine.  This interface can exist even on a machine that has no
physical network ports at all.

On your system, you probably have something like this collection of
interface names and associated addresses ("ip address" will show you
much more detail, and there will very likely be other addresses such as
IPv6 addresses which I've left out for brevity):

  lo: 127.0.0.1
  eth0: 192.168.178.20

/etc/hosts will cause localhost to resolve to 127.0.0.1, because that
pretty much always exists and can be set as a constant.  In contrast,
192.168.178.20 isn't necessarily a constant property of your machine -
if you took it away and plugged it into some other network it would
probably get a different address - and it would be much more awkward to
arrange for localhost to resolve to whatever it happens to be at the
current time, not to mention the situation with hosts that have multiple
externally-visible addresses.

Now, when a server binds a socket so that it can receive packets on it,
it typically either binds to a port on all the host's network interfaces
(programs do this using a constant called INADDR_ANY, and you may
sometimes see references to this in documentation) or to a specific
address and port.  If it does the latter, it will only receive packets
whose destination is that particular address, not any other address that
the host may happen to possess even if the port is correct.  It sounds
like the server in question here bound itself specifically to
localhost:8080, i.e. 127.0.0.1:8080 after name resolution, in which case
it won't also be listening on 192.168.178.20:8080.

You can see (for example) which listening TCP sockets are open on your
system like this:

  sudo ss -lnpt

... or, without abbreviation:

  sudo ss --listening --numeric --processes --tcp

In this output, local addresses shown as "*" indicate a socket bound to
all the host's network interfaces.

-- 
Colin Watson                                       [cjwatson at ubuntu.com]




More information about the ubuntu-users mailing list