java网络编程入门到精通



































 

InetAddress类:

public class NetTest {
    /**设定缓存的属性**/
    public static final String PROPERTY_NETCACHE = "networkaddress.cache.ttl";
    /**异常信息缓存属性**/
    public static final String PROPERTY_EXCEPTIONCACHE = "networkaddress.cache.negative.ttl";
    
    public static void main(String[] args) throws IOException {
        /*
         * 初始化InetAddress host既可以是主机名也可以是ip地址 addr是以字节数组表示的ip地址
          * 1:InetAddress.getByName(String host) 返回该主机所对应的第一个主机名/ip
         * 2:InetAddress.getLocalHost() 返回本地主机 主机名/ip
         * 3:InetAddress.getAllByName(String host) 返回该主机对应的所有 主机名/ip
         * 4:InetAddress.getByAddress(byte[] addr) 返回 主机名/ip
         * 5:InetAddress.getByAddress(String host, byte[] addr) 返回主机名/ip
         */
        InetAddress ia = InetAddress.getByName("www.baidu.com");
        out.println(ia);
        
        InetAddress localIp = InetAddress.getLocalHost();
        out.println(localIp);
        
        InetAddress[] allIpAddress = InetAddress.getAllByName("www.google.com");
        for (InetAddress address : allIpAddress){
            System.out.println(address);
        }

        InetAddress byAddress = InetAddress.getByAddress(new byte[]{74,125,71,103});
        out.println(byAddress);
        
        InetAddress byHostAddress = InetAddress.getByAddress("www.baidu.com", new byte[]{119,75,218-256,45});
        out.println(byHostAddress);
        /*
         * 设置缓存超时 单位秒 -1表示一直缓存  
          * 设置了缓存机制,第二次访问该dns服务器就直接读缓存
          */
        Security.setProperty(PROPERTY_NETCACHE, "-1");
        /*
         * 设置异常信息缓存秒数
          */
        Security.setProperty(PROPERTY_EXCEPTIONCACHE, "10");
        //判断能否连接
        System.out.println(ia.isReachable(100));
        /*
         * 获取ip字符串 
          */
        out.println(ia.getHostAddress());
        /*
         * 获取该ip地址的主机别名 InetAddress由ip创建 返回主机名
          */
        out.println(ia.getHostName());
        /*
         * 获取该ip地址的主机名
          */
        out.println(ia.getCanonicalHostName());
        /*
         * 获取字节数组组成的ip地址
          */
        out.println(ia.getAddress());
        /*
         * 使用ip创建的InetAddressgetHostName()才访问服务器
          */
        out.println(byAddress.getHostName());
        /*
         * Mire字符串的转换
          * URLDecoder 特殊---->一般 URLEncoder 一般---->特殊
          */
        //解码
        String keyWord = URLDecoder.decode("%E8%8D%89%E6%B3%A5%E9%A9%AC", "UTF-8");
        out.println(keyWord);
        //编码
        String keyWordd = URLEncoder.encode(keyWord, "UTF-8");
        out.println(keyWordd);
    }
}




 

发布了9 篇原创文章 · 获赞 2 · 访问量 4万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章