【Java学习笔记】显示IP

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) {
        }
    }
}


本文转自gnuhpc博客园博客,原文链接:http://www.cnblogs.com/gnuhpc/archive/2012/12/17/2822294.html,如需转载请自行联系原作者
上一篇:android 百度地图开发


下一篇:Java Socket基础(二)