在没有网络的情况下,在命令行ping localhost与ping 127.0.0.1也是可以ping通的(前提需有网卡),但两者有到底有区别吗?有联系吗?
我现在的理解是localhost是127.0.0.1的一个别名,两者是通过C:\WINDOWS\system32\drivers\etc\hosts(在此假定系统盘为C盘)这个文件来对应起来的。用记事本打开这个文件,内容如下:
# Copyright (c) 1993-1999 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host
127.0.0.1 localhost
在这个文件的最后一行写明了127.0.0.1与localhost的对应关系,我们不防来做个实验,在这个文件最后加下面一行:
127.0.0.1 happy
保存之后,再打开命令行,ping happy,你会发现,现在happy也可以ping 通了,由此可知localhost只是大家约定的代表127.0.0.1的一个别名,如果你喜欢,你可以通过上面这种方式为127.0.0.1配置不同的别名。