获取地址

 

 
public class GetIpAddress
{
    //获取本机IP地址
    public static String getLocalIp()throws UnknownHostException
    {
        InetAddress addr=InetAddress.getLocalHost();
        return addr.getHostAddress();
    }
 
    //获取本机机器名
    public static String getLocalName()throws UnknownHostException
    {
        InetAddress addr=InetAddress.getLocalHost();
        return addr.getHostName();
    }
 
 
    //根据域名获取主机Ip地址
    public static String[] getAllIpByName(String hostName) throws UnknownHostException
    {
        InetAddress []addr=InetAddress.getAllByName(hostName);
        String []ips=new String[addr.length];
        for(int i=0;i<ips.length;i++)
        {
            ips[i]=addr[i].getHostAddress();
        }
        return ips;
    }
    public static String getIpByName(String hostName) throws UnknownHostException
    {
        InetAddress addr=InetAddress.getByName(hostName);
 
        return addr.getHostAddress();
    }
 
    public static void main(String[] args)
    {
        // TODO 自动生成的方法存根
        try
        {
            System.out.println("本机ip: "+getLocalIp());
            System.out.println("本机名字: "+getLocalName());
        //某网站的ip
            String zhihu="www.zhihu.com";
            //System.out.println("知乎的IP:"+getIpByName(zhihu));
 
 
            String []zhiHuIps=getAllIpByName(zhihu);
            System.out.println("知乎的IP:"+zhiHuIps.length);
            for(int i=0;i<zhiHuIps.length;i++)
            System.out.println(zhiHuIps[i]);
 
 
        } catch (Exception e)
        {
            // TODO: handle exception
            System.err.println("找不到网址");
            //e.printStackTrace();
        }
    }
 
}
 
 
posted @ 2016-07-27 11:06  -梦里不知身是客  阅读(208)  评论(0编辑  收藏  举报