In java, what's the difference between InetAddress.getLocalHost() and InetAddress.getByName(“127.0.0.1”)
我正在将Windows 8与JDK 1.7一起使用。运行时,我的IP地址为192.168.1.108:
1 |
或
1 |
输出-全部为假。
1 2 | InetAddress.getLocalHost() - Output: 192.168.1.108 InetAddress.getByName("localhost") - Output: 127.0.0.1 |
此外,我的UDP服务器已绑定在
有人知道区别吗?预先感谢。
来自JDK文档的getLocalHost():
Returns the address of the local host. This is achieved by retrieving the name of the host from the system, then resolving that name into an InetAddress.
在我的GNU / Linux框中,我的主机名是" laptop",它映射到与/ etc / hosts中的127.0.0.1不同的地址。 Windows中的等效文件位于C:\\\\ Windows \\\\ System32 \\\\ drivers \\\\ etc \\\\ hosts。
默认情况下,在DNS查找之前会搜索此主机文件。
广告1似乎可以在您的LAN / WAN中为您提供地址
(我指的是本地/专用网络IP地址,例如
192.168.0.108或类似10.3.6.55)。
另请参见:
http://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
http://download.java.net/jdk7/archive/b123/docs/api/java/net/InetAddress.html#getLocalHost()
但是请注意,在我的示例中ad2和ad3相等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import java.net.InetAddress; public class Test014 { public static void main(String[] args) throws Exception { InetAddress ad1 = InetAddress.getLocalHost(); InetAddress ad2 = InetAddress.getByName("localhost"); InetAddress ad3 = InetAddress.getByName("127.0.0.1"); printArr(ad1.getAddress()); printArr(ad2.getAddress()); printArr(ad3.getAddress()); System.out.println(ad1.equals(ad2)); System.out.println(ad1.equals(ad3)); System.out.println(ad2.equals(ad3)); } static void printArr(byte[] arr){ for (int i=0; i<arr.length; i++){ System.out.print("[" + i +"] =" + arr[i] +";"); } System.out.println(); System.out.println("---------"); } } |
此外,请查看API文档,了解equals方法何时返回true和false。
http://download.java.net/jdk7/archive/b123/docs/api/java/net/InetAddress.html#equals(java.lang.Object)