注:本文只讨论进程监听时三个地址的区别。
通俗地讲
127.0.0.1
代表本机地址。比如,一个进程监听了127.0.0.1:8080
,只有本机的其他进程才可以访问,外网或局域网的进程无法访问。localhost
指向127.0.0.1
,可以理解为是127.0.0.1
的别名,定义在/etc/hosts
(OS: *nixes)文件中。0.0.0.0
代表本机器的所有地址,不仅包括:127.0.0.1
,还包括本机其他地址。比如,本机除了127.0.0.1
,还包括两个局域网IP192.168.0.8
,10.10.0.8
,当某个进程监听0.0.0.0:8080
,本机进程通过127.0.0.1:8080
、局域网A通过192.168.0.8:8080
、局域网B通过10.10.0.8:8080
都可以访问该进程。
Loopback Address/环回地址/环回地址
127.0.0.1
是环回地址,环回地址是本机网卡的保留地址,不需要经过网络直接分配给本机。- 环回地址可以绕开TCP/IP 协议栈的下层,效率更高
/etc/hosts
This file is a simple text file that associates IP addresses with hostnames, one line per IP address. For each host a single line should be present with the following information:
IP_address canonical_hostname [aliases…]
本机/etc/hosts
:1
2
3
4
5
6
7
8
9##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
BTW
mysql -uroot -hlocalhost
通常会报错ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
.
但是mysql -uroot -h127.0.0.1
却可以成功连上数据库,但是上文说localhost
是127.0.0.1
的别名,为什么此处又不同呢?
查阅mysql官网,找到如下内容:
On Unix, MySQL Shell connections default to using Unix sockets when the following conditions are met:
- A TCP port is not specified.
- A host name is not specified or it is equal to localhost.
- The –socket or -S option is specified, with or without a path to a socket file.
原来这是mysql的特殊约定,主机名为localhost
会连接本地的Unix sockets