通过Java1.6的jdk获取中文计算机名称时,存在一个bug。
前提条件
代码如下:
public class NetAddress { public static void println(String s, InetAddress address){ String sName = address.getHostName(); String sIp = address.getHostAddress(); System.out.println(s + "_" + sName + "_" + sIp); System.out.println("名称byte数组:" + Arrays.toString(sName.getBytes())); } public static void main(String[] args) throws UnknownHostException{ // NetAddress n = new NetAddress(); // n.show2(); // 本地 InetAddress address1 = InetAddress.getLocalHost(); println("local", address1); // InetAddress address2 = InetAddress.getByName("10.36.24.17");; println("getByName", address2); InetAddress address3 = InetAddress.getByName("127.0.0.1");; println("127.0.0.1", address3); InetAddress address4 = InetAddress.getByName("");; println("空", address4); } }
以上程序,通过4种方法获取计算机的信息,并分别打印计算机的名称和IP,同时把计算机名称byte字节流也逐一打印出来。
执行程序,打印信息如下:
local_????????_ENGLIS_10.36.24.17 名称byte数组:[63, 63, 63, 63, 63, 63, 63, 63, 95, 69, 78, 71, 76, 73, 83] getByName_中文名称_ENGLISH_10.36.24.17 名称byte数组:[-42, -48, -50, -60, -61, -5, -77, -58, 95, 69, 78, 71, 76, 73, 83, 72] 127.0.0.1_localhost_127.0.0.1 名称byte数组:[108, 111, 99, 97, 108, 104, 111, 115, 116] 空_localhost_127.0.0.1 名称byte数组:[108, 111, 99, 97, 108, 104, 111, 115, 116]
结论:
从打印信息可以看出:
bug无处不在,没想到JDK自带类也存在bug