1:InetAddress是ip地址的高级表示。下面介绍其常用方法。
1.1:getByName():静态方法,接受要查找的主机名作为参数,如下:
InetAddress ia = InetAddress.getByName("localhost"); System.out.println(ia.getHostName()); System.out.println(ia.getHostAddress());
输出结果为:
localhost 127.0.0.1 1.2:getAllByName():给定一个主机名,返回一个数组,包含所有对应此主机名的地址,如下:
InetAddress[] ias = InetAddress.getAllByName("www.baidu.com"); for (int i = 0; i < ias.length; i++) { System.out.println(ias[i]); }
输出结果为:
www.baidu.com/119.75.217.109 www.baidu.com/119.75.218.70
1.3:getHostName():返回一个包含主机名的字符串,如果没有主机名则返回ip;getHostAddress():返回ip;
InetAddress ia = InetAddress.getByName("192.168.0.107"); System.out.println(ia.getHostName()); System.out.println(ia.getHostAddress());
输出结果为:
chu 192.168.0.107
1.4:使用InetAddress查找局域网内所有的主机名和ip地址,如下:
private void search(){ for(int num = 0; num <= 255; num++) { final String host = "192.168.0." + num; new Thread() { public void run() { try { InetAddress hostAddress = InetAddress.getByName(host); if(!hostAddress.getHostName().equalsIgnoreCase(hostAddress.getHostAddress())) System.out.println(hostAddress.getHostName()+":"+host); }catch(UnknownHostException e) { e.printStackTrace(); } } }.start(); } }
输出结果如下:
chu:192.168.0.107 CHINA-8903D0A7B:192.168.0.160 20100923-0243:192.168.0.101 KWH6ZHNESMCDDZC:192.168.0.104 PC-201011082204:192.168.0.114 深度系统:192.168.0.103 PC-20121013RPCE:192.168.0.164 ZKNRQ9CWBFAVQF8:192.168.0.111 DADI-PC:192.168.0.102 WAYSOFT:192.168.0.170 ADMIN_PC:192.168.0.211 KIN-PC:192.168.0.216 WIN-ELL8LDIF2H9:192.168.0.106
2:NetworkInterface表示物理硬件和虚拟地址。
2.1:使用NetworkInterface返回本地ip
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces(); while (netInterfaces.hasMoreElements()) { NetworkInterface nif = netInterfaces.nextElement(); Enumeration<InetAddress> iparray = nif.getInetAddresses(); while (iparray.hasMoreElements()) { InetAddress ip = iparray.nextElement(); System.out.println(ip.getHostAddress()); } }
输出结果为:
127.0.0.1 192.168.0.107