【Java学习笔记】显示IP
作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/
import java.net.InetAddress; import java.net.UnknownHostException; import java.io.IOException; public class ShowIP { public static void main(String arg[]) { InetAddress address; try { address = InetAddress.getByName("g.cn"); showAddress(address); address = InetAddress.getLocalHost(); showAddress(address); byte a[] = { 127,0,0,1 }; address = InetAddress.getByAddress(a); showAddress(address); } catch(UnknownHostException e) { System.out.println(e); } } static void showAddress(InetAddress address) { byte a[] = address.getAddress(); System.out.println(address.getHostName() + ": " + (a[0] & 0xFF) + "." + (a[1] & 0xFF) + "." + (a[2] & 0xFF) + "." + (a[3] & 0xFF));//与0xFF做与运算,把符号位剔除 if(address.isLoopbackAddress()) System.out.println(" (the loopback address)"); try { if(address.isReachable(30000)) System.out.println(" (is reachable)"); } catch(IOException e) { } } }